Usage (v1)
Use bootstrapValidate()
The API is intentionally small. Pass an input selector or element, a rule string, and optionally a callback. Since v2.3.0, the call returns a validation handle.
The Function
bootstrapValidate('#myInput', 'required:Please fill out this field!', function (isValid) { if (isValid) { console.log('Element is valid'); }});Selectors and Elements
The first argument works like document.querySelector(). You
can pass an id, class, attribute selector, DOM element, or an array of
selectors/elements.
bootstrapValidate(['#firstName', '#lastName'], 'max:20:Enter no more than 20 characters');Rules and Options
Separate multiple rules with |. Separate rule options with
:. The final option is the error message.
bootstrapValidate('#email', 'required:Required|email:Enter a valid email');Submit Validation
Store the returned handles when a form must validate before submit.
const validators = [ bootstrapValidate('#email', 'required:Email required|email:Enter a valid email'), bootstrapValidate('#password', 'required:Password required'),];
document.querySelector('#account').addEventListener('submit', (event) => { const isValid = validators.map((validator) => validator.validate()).every(Boolean); if (!isValid) { event.preventDefault(); }});Remove Listeners
const validator = bootstrapValidate('#email', 'email:Enter a valid email');validator.destroy();Optional Fields
Empty fields pass non-required rules. Combine a rule with required when the field must be filled out.
bootstrapValidate('#website', 'url:Enter a valid URL');bootstrapValidate('#email', 'required:Required|email:Enter a valid email');Regex Separators
Regex rules can contain pipes. Escape a pipe or colon when it would look like a rule separator.
bootstrapValidate( '#time', 'regex:([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])\\s*([AaPp][Mm]):Please enter a valid time');
bootstrapValidate('#slug', 'regex:foo\\|bar\\:baz:Invalid slug');Select and Select2
Native selects are validated on change. Select2 works by triggering the original select element's change event.
bootstrapValidate('#group', 'required:Choose a group');Custom Rules
Version 2 supports synchronous custom rules. Async checks belong in the v3 API.
bootstrapValidate.extendRule('evenLength', (input) => input.value.length % 2 === 0);bootstrapValidate('#code', 'evenLength:Use an even number of characters');Rule Reference
Browse the available validation rules and copy ready-to-use examples.