addField
Defines validation rules for the new field.
The method return a JustValidate instance, so it could be used as a chain (like .addField().addField()...
).
The method takes 3 arguments:
addField(field, rules, config);
where:
field
- a string selector or DOM element of the field
rules
- array of validation rule objects (described here)
config
- some specific settings applied to this particular field. Replace settings from default config (described here):
errorFieldCssClass
Overrides errorFieldCssClass
errorFieldStyle
Overrides errorFieldStyle
errorLabelCssClass
Overrides errorLabelCssClass
errorLabelStyle
Overrides errorLabelStyle
successFieldCssClass
Overrides successFieldCssClass
successFieldStyle
Overrides successFieldStyle
successLabelCssClass
Overrides successLabelCssClass
successLabelStyle
Overrides successLabelStyle
tooltip
Overrides tooltip
errorsContainer
Overrides errorsContainer
successMessage
Custom text if the field is valid (validation passes for all rules).
Type: string
Default value: undefined
(success messages are not shown)
Example
const validation = new JustValidate('#form');
validation
.addField('#name', [
{
rule: 'name',
},
{
rule: 'minLength',
value: 3,
},
{
rule: 'maxLength',
value: 20,
},
])
.addField(
'#email',
[
{
rule: 'required',
},
{
rule: 'email',
},
{
validator: (value) => () =>
new Promise((resolve) => {
isEmailExist(value).then((isExist) => {
resolve(!isExist);
});
}),
errorMessage: 'Email already exists!',
},
],
{
errorsContainer: '.custom-errors-container',
successMessage: 'Everything looks good!',
}
);
Also, it's possible to do validation based on other fields:
const validation = new JustValidate('#form');
validation.addField('#repeat-password', [
{
validator: (value, fields) => {
if (fields['#password'] && fields['#password'].elem) {
const repeatPasswordValue = fields['#password'].elem.value;
return value === repeatPasswordValue;
}
return true;
},
errorMessage: 'Passwords should be the same',
},
]);