Define Rules
Simple Fields
You can define validation rules for simple fields using the items
property of the ValidatorConfig. This property accepts an object where you specify the fields to validate. The object should include only the fields of the type passed to v.validator<Type>
. Each field is of type ItemType
.
type ItemType<T, TContext> = {
[K in keyof T]?: TypeValidator<T[K]> | TypeValidatorWithContext<T[K], TContext>[];
}
Note:
TypeValidatorWithContext
is used to define validation rules that depend on contextual information. For example, validations based on the context of the application or specific data dependencies.
Defining Validation Rules for Simple Fields
Here's how you can define validation rules for individual fields:
<fieldName>: v.<validatorMethod>.<rule1()>...
In this structure:
validatorMethod
refers to predefined methods provided by the library (v
) to createTypeValidator
objects containing validation rules.rule1
,rule2
, etc., are methods or functions chained together to specify validation criteria such as required fields, string length, format, etc. (read more)
This approach allows you to configure detailed validation requirements for each field in your data type, ensuring data integrity and consistency in your application.
Example
v.validator<User>({
id: 'validator id',
items: {
username: v.string().required(),
age: v.number().positive(),
password: v.string().onError({
error: (value) => {
// Custom validation logic to ensure password complexity
return true;
},
message: 'Password must be complex'
})
}
})