From the documentation http://1000hz.github.io/bootstrap-validator/:
Add custom validators to be run. Validators should be functions that receive the
First of all add your own custom validator, for example:
var validatorOptions = {
delay: 100,
custom: {
unique: function ($el) {
var newDevice = $el.val().trim();
return isUniqueDevice(newDevice)
}
},
errors: {
unique: "This Device is already exist"
}
}
Second, you need to "bind" the form input for the custom validator, for example:
<input id="add_new_device_input" class="form-control" data-unique="unique">
If you want to add to this input more validators error you must to add the custom error to the input: data-unique-error="This device is already exist" for example:
<input id="add_new_device_input" class="form-control" data-unique="unique" data-unique-error="This device is already exist" data-error="The Device pattern is invalid" pattern="<Add some regex pattern here>">
The "data-error" is the default validator error and it called "native" key, the following code will demonstrate how the validator print the error messages according to the validator key:
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
I wanted to flesh out the answers here with a bit more detail.
I was attempting to do this while using the data-api (putting data-toggle="validator"
in the form tag). Removing that from my <form>
tag and enabling it with Javascript, my custom function works:
$('#sign-up_area').validator({
custom: {
'odd': function($el) { return Boolean($el.val() % 2);}
},
errors: {
odd: "That's not an odd number!"
}
});
I also had to add a value to the data-odd attribute thusly:
<div class="row">
<div class="form-group col-xs-12 col-md-12">
<label class="control-label" for="test">Odd/Even:</label>
<input type="text" name="test" id="test" class="form-control" placeholder="Enter an odd integer" data-odd="odd" >
<span class="help-block with-errors"></span>
</div>
</div>
Interesting to note that if I add the following to the <input>
element, it takes precedence over the error message declared in javascript:
data-odd-error="Not an odd number, yo!"
However, I get an error in console if I only use the data-odd-error attribute but NO error message specified in Javascript. Thus, you must declare an error message in Javascript.
You need to call your plugin manually, as custom
options will not work with data-attributes:
$().validator({
custom: {
'odd': function($el) { return Boolean($el.val() % 2);}
}
})
then use it like this:
<input placeholder="plz enter odd value" data-odd>
Don't forget to add error messages, see code