How to use custom validators of github.com/1000hz/bootstrap-validator

leo picture leo · Apr 21, 2015 · Viewed 18.9k times · Source

From the documentation http://1000hz.github.io/bootstrap-validator/:

Add custom validators to be run. Validators should be functions that receive the jQuery element as an argument and return a truthy or falsy value based on the validity of the input.

Object structure is: {foo: function($el) { return true || false } }

Adding the validator to an input is done just like the others, data-foo="bar".

You must also add default error messages for any custom validators via the errors option.

I don't quite understand how to define my own custom validator and how to use it with this plugin.

Could anyone give me a simple example or hint?

Answer

julesbou picture julesbou · Apr 21, 2015

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