callback validator
Check if the input value passes a callback method
Options
Using with form field
(* denotes a required option)
Name | HTML attribute | Type | Description |
---|
callback * | data-fv-callback___callback | Function | The callback method |
message | data-fv-callback___message | String | The error message |
The callback method must follow the format below:
function(input) {
return true;
}
If you want to return a dynamic message, the callback function must return an object containing the valid
and message
members:
function(input) {
if (...) {
return {
valid: true,
message: 'The error message'
};
}
return {
valid: false,
message: 'Other error message'
};
}
Look at the
Alias plugin if you want to have multiple callbacks on the same field
Using the ES6 module
import { callback } from '/vendors/@form-validation/cjs/validator-callback';
const result = callback().validate({
value: ...,
options: {
callback: ...,
},
},
});
Using the npm package
- Install the validator package:
$ npm install @form-validation/validator-callback
- Use the
callback
validator:
import { callback } from '@form-validation/validator-callback';
const result = callback().validate({
value: ...,
options: {
callback: ...,
},
});
Basic example
In the following form, user is asked to enter a correct answer of simple operation which is generated randomly.
NPM package example
The following snippet shows how to use the callback validator with ES6 module to check if a password is strong or weak:
import callback from '/vendors/@form-validation/cjs/validator-callback';
const validatePassword = function (input) {
const value = input.value;
if (value === '') {
return { valid: true };
}
if (value.length < 8) {
return {
valid: false,
message: 'Password must have at least 8 characters',
};
}
if (value === value.toLowerCase()) {
return {
valid: false,
message: 'Password must have at least one uppercase character',
};
}
if (value === value.toUpperCase()) {
return {
valid: false,
message: 'Password must have at least one lowercase character',
};
}
if (value.search(/[0-9]/) < 0) {
return {
valid: false,
message: 'Password must have at least one digit',
};
}
return { valid: true };
};
const res1 = callback().validate({
value: '123456',
options: {
callback: validatePassword,
},
});
const res2 = callback().validate({
value: 'not.contains.upper',
options: {
callback: validatePassword,
},
});
const res3 = callback().validate({
value: 'not@CONTAIN@digit',
options: {
callback: validatePassword,
},
});
const res4 = callback().validate({
value: 'v@l1dP@@',
options: {
callback: validatePassword,
},
});
See also
Changelog