Validate your forms in vanilla js.
Create validator :
// Get form dom element
var form = document.getElementsByTagName('form')[0];
// Create validator
var validator = new VanillaFormValidator(form);
Add a field to validator :
validator.addField('field_name', {
validators: {
not_empty: {
message: 'This field is required'
}
}
});
Or add mutiple fields :
var fields = {
"field_name": {
"validators": {
not_empty: {
message: 'This field is ...'
}
}
},
"field_name": {
"validators": {
not_empty: {
message: 'This field is ...'
}
}
}
}
validator.addFields(fields);
Check validity of form :
// Return true or false
validator.valid();
Get form errors :
// Return hash of errors
validator.errors();
Display error messages :
// Append small html tag to input with message
validator.validate();
Live validations :
// Listen on click, change and keyup events on form inputs
// Use preventDefault() on submit event if form is not valid
validator.initLive();
Reset validations :
// Remove values, events and messages
validator.reset();
Remove error messages :
validator.clearErrorMessages();
You can simply add rule :
// Function must return boolean
// True if field id valid, else false
VanillaFormValidator.addRule('rule_name', function(value, opts){
// dom element is stored in opts['element']
});
Then you can call your rule when you declare your fields
- Fork it ( https://github.com/angelodlfrtr/vanilla-form-validator/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request