bValidator

bValidator is a form validation jQuery plug-in.

It supports themes for validation messages, various validation functions, validation of dynamic forms, server side validation and more (see examples).

This page contains documentation for version 1.x, if you are looking for an older version click here.

Setup

Download Download bValidator from here (currently v1.0.5) Or install with Bower: $ bower install bvalidator Or install with npm: $ npm install bvalidator Git repository: https://github.com/bmauser/bvalidator.git Include JavaScript To use bValidator you need to include jQuery, jquery.bvalidator.min.js and .js and .css files for the theme you want to use. <script src="jquery.min.js"></script> <script src="jquery.bvalidator.min.js"></script> // for choosen theme <script src="themes/presenters/default.min.js"></script> <script src="themes/gray/gray.js"></script> Include CSS for the theme <link href="themes/gray/gray.css" rel="stylesheet" /> HTML The page should contain inputs you want to validate: <form data-bvalidator-validate> Email: <input type="text" data-bvalidator="required,email"/> Url: <input type="text" data-bvalidator="url"/> </form> Add data-bvalidator-validate attribute to the <form> you want to validate to bind bValidator to the form.

To each you want to validate, add data-bvalidator attribute with validation functions to invoke for the field. With JavaScript You can also bind bValidator to the form with JavaScript (in that case data-bvalidator-validate attribute is not needed on the <form> ). You can use jQuery's $(document).ready to execute the script as soon as the web page has been loaded: <script type="text/javascript"> $(document).ready(function () { $('form').bValidator(); }); </script> Upgrade form version 0.x bValidator 1.x is not backward compatible with version 0.x. Basic features are similar to those in 0.x, but I have introduced a lot of changes into 1.x without backward compatibility in mind. Please read this docs before upgrade.

Options

bValidator first checks default options. You can change default options like this: <script type="text/javascript"> bValidator.defaultOptions.singleError = true; bValidator.defaultOptions.useTheme = 'red'; </script> You can also set options by passing an object with options to the constructor function: <script type="text/javascript"> var options = { singleError: true, useTheme: 'orange' }; $('#myform').bValidator(options); </script> bValidator also checks for options set by data-bvalidator-option- attribute on the <form> element. For example, for singleError use the data-bvalidator-option-single-error attribute name: <form data-bvalidator-option-single-error="true" data-bvalidator-validate> <input type="text" data-bvalidator="number,required"/> </form> Option name Default value Description singleError false If true , only the first validation message will be shown. scrollToError true The page will be scrolled up or down to make the first message visible. scrollToErrorOffset -10 Offset from the top of the browser window. lang "en" Language for validation messages. useTheme "" Theme for validation messages. delayValidation 300 Delay in milliseconds to invoke validation after validateOn and errorValidateOn events. true If true , validation will occur on form submit (if validator is bind to a form). stopSubmitPropagation true If true , submit event propagation will be stopped on validation error (if validator is bind to a form). This option is considered only if the value of validateOnSubmit option is true . autoModifiers {'digit': ['trim'],

'number': ['trim'],

'email': ['trim'],

'url': ['trim'],

'date': ['trim'],

'ip4': ['trim'],

'ip6': ['trim']} This option tells which modifiers are automatically called for a validation function. trim modifier is called for stated functions by default, so you don't have to explicitly put the modifier into data-bvalidator-modifier attribute. You can set more auto modifiers for one validation function and use parameters as in data-bvalidator attribute. For example:

'mycheck': ['trim', 'myMod', 'myMod2[1:3]'] ajaxValid "ok" Valid response for server side validation with ajax validation function. If the value is valid, Ajax request should return this string. ajaxResponseMsg false If true , a response from the server is used as the validation message. ajaxOptions {cache: false, method: 'POST'} Options for Ajax request. See jQuery documentation. ajaxParams null Object (or function that returns an object) with values that are sent to the server with the request. For example: {'id':123} . ajaxUrl "" URL for Ajax request. If empty, current browser URL is used. ajaxCache true If true , Ajax response from the server will be cached and the response from cache will be used if the input value is not changed since the last Ajax call. skipValidation ":hidden, :disabled" jQuery selector to filter out inputs that will be skipped by bValidator (only inputs with data-bvalidator attribute are considered). noMsgIfExistsForInstance [] This option can be useful if you are using more bValidator instances on the same form and you don't want to show a message if a message is already shown for the instance specified by this option. If a message is already shown it will not be removed. Example: ["myinstance"] paramsDelimiter ":" Delimiter for validation function arguments inside square brackets [] in data-bvalidator attribute. actionsDelimiter "," Validator functions delimiter in data-bvalidator attribute. html5ValidationOff true If true , HTML5 validation will be disabled for the forms bValidator is bound to. enableHtml5Attr true If true , bValidator will validate HTML5 input types: email , url , number

and inputs with attributes: min , max , minlength , maxlength , pattern , required . forceValidationResult null Set to true or false to force validation result for all inputs inside the form. Also see theme options.

Messages and translations

bValidator can retrieve validation messages from: validation function

data-bvalidator-msg attribute

attribute data-bvalidator-msg-functionName attribute

attribute configuration object (options)



server response (example) See examples. You can use {0} , {1} , {2} , {3} , ... tags in the validation message and they will be replaced with validation function parameters in [] . You can change default messages or add new ones by changing default options: <script type="text/javascript"> bValidator.defaultOptions.messages.en.email = 'Invalid email'; bValidator.defaultOptions.messages.en.mycheck = 'Correct this'; </script> or pass messages as options to validator constructor: <script type="text/javascript"> var options = { lang: 'hr', messages: { hr: { 'default': 'Ispravite ovu vrijednost.', 'equalto': 'Unesite ponovno istu vrijednost.', 'differs': 'Unesite različitu vrijednost.', // .... } } }; $('#myform').bValidator(options); </script> All default messages in English are listed in jquery.bvalidator.js file. For some other languages, there are .js files in lang folder. If you create a translation file, please make a pull request on GitHub and I will merge it into the project.

Validation and modifying functions

Validation functions (validators) are functions that check the value and return true if the value is valid. Modifying functions (modifiers) are functions that change the value of the field before validation, for example, to trim whitespace. Modifiers return a modified value. Validations which will be invoked for an input are listed by default in data-bvalidator attribute. Modifiers are listed in data-bvalidator-modifier attribute. Some functions can have parameters which are stated in square brackets [] and delimited with : , for example: mycheck[param1:param2:param3] . <input type="text" data-bvalidator="maxlength[10]" data-bvalidator-modifier="trim" /> <input type="text" data-bvalidator="max[10],email,required" /> Here are listed all built-in validation functions, but you can easily add your own. Validator Parameters Description alpha Checks if all characters are alphabetic. Empty space ( ' ' ), underscore( _ ), minus ( - ) and period ( . ) are also valid. alphanum Checks if all characters are alphanumeric. Empty space ( ' ' ), underscore( _ ), minus ( - ) and period ( . ) are also valid. digit Checks if all characters are digits. number Checks if the input value is a number. email Checks if the input value is an E-mail. url Checks if the input value is a valid URL. date date format Checks if the value is a valid date in the format specified by the function parameter. A format can be any combination of mm , dd , yyyy with one character separator between. Example: date[mm.dd.yyyy] or date[yyyy-mm-dd] required Sets a field as required. If you put required in front of other functions like data-bvalidator="required,max[10],email" , a message that the field is required will be shown with other validation messages. If you put required after other functions like data-bvalidator="max[10],email,required" , a message that the field is required will not be shown if there are other validation messages. Note that if a field is not marked as required and it is empty, it will be considered as valid and not validated at all. For example, if you have a field with data-bvalidator="email" and you leave it empty, email validation function will not be called on the form submit. If a field is not required, but you still want the validator to be called, use valempty function. between minimum value maximum value Checks if the value is between values set by function parameters. Example: between[5:10] If this function is used with multi-select or checkbox in a group (checkboxes with the same name, for example name="chk[]" ), it means that a number of selected options or checkboxes must be between values set by function parameters. See example. max maximum value Checks if the value is less or equal to the function parameter. If this function is used with multi-select or checkbox in a group (checkboxes with the same name for example name="chk[]" ), it means that a number of selected options or checkboxes must be less or equal to the function parameter. See example. min minimum value Checks if the value is greater or equal to the function parameter value. If this function is used with select or checkbox in a group (checkboxes with the same name for example name="chk[]" ), it means that a number of selected options or checkboxes must be greater or equal to the function parameter. See example. rangelen minimum length maximum length Checks if length of the value is between values of function parameters. Example: rangelen[5:20] maxlen maximum length Checks if length of the value is smaller than the function parameter value. Example: maxlen[20] minlen minimum length Checks if length of the value is greater than the function parameter value. Example: minlen[5] extension file extensions Checks if the value ends with ' . ' followed by any of passed parameters. Example: extension[jpg:png:txt]

ip4 Checks if the value is a valid IPv4 address. ip6 Checks if the value is a valid IPv6 address.

Note that this function uses a complex regular expression which can be pretty slow. valempty Validates field even if it's not marked as required and is empty. This function makes sense only if some other custom validation function is used on that field and the field is not required . See example. ajax Function for server side validation. See examples. differ element ID Input value has to be different from the value of the field whose ID is passed as parameter. Example: equal[myElementId] equal element ID Input value has to be equal to the value of the field whose ID is passed as parameter. Example: differ[myElementId] pattern pattern modifier (optional) Checks if the value matches a regular expression pattern given by the function parameter.

If the pattern contains characters like [] , : (same characters used by bValidator to parse function arguments), you'll have to use a custom validation function or use HTML5 pattern attribute. Modifying functions Modifier Parameters Description trim Removes whitespace from the beginning and the end of the input value. Custom modifiers can be added in the same way as custom validation functions (see example).

API functions

When you make an instance of bValidator you can call some functions on that instance. You can get reference to a validator instance using jQuery data function: <script type="text/javascript"> $('#myform').bValidator(); // check if form is valid if($('#myform').data('bValidator').isValid()){ // do somenthing } </script> .data('bValidator') returns reference to the first instance of bValidator. You can have more instances of bValidator on the same form (see example) and all references are returned by .data('bValidators') (note the 's' here). <script type="text/javascript"> // first instance $('#myform').bValidator(); // second instance with default options and named 'myinstance' $('#myform').bValidator(null, 'myinstance'); // validates the form with the first instance named 'bvalidator' $('#myform').data("bValidators").bvalidator.validate(); // validates the form with the second instance named 'myinstance' $('#myform').data("bValidators").myinstance.validate(); </script> Instance names can be also set by data-bvalidator-validate attribute. Default instance name is bvalidator . Instance names are in lower case. Function Arguments Description isValid jQuery object containing inputs to check

(optional) Only checks if inputs are valid. Doesn't show validation messages. Returns true if all fields are valid, or false if there are some validation errors. getOptions Returns the object with options of the current validator instance. showMsg jQuery object containing inputs string message (optional) Shows a message on the elements specified with the first argument. Message can be shown on any element on the page. The element doesn't have to be a part of the form (or container element) on which bValidator is bound. If the second argument is not set, bValidator will try to get a message from data-bvalidator-msg attribute. removeMsg jQuery object containing inputs Removes the message. getInputs Returns jQuery object containing all input fields associated with the validator. getForm Returns jQuery object containing <form> (or other element on which bValidator is bound). reset jQuery object containing inputs

(optional) Hides all validation messages and unbinds events. This function is bind to the form reset event. destroy Removes bValidator instance. getValidators Returns the object with all built-in validation functions of the current validator instance. This is useful for adding custom validator functions which are not accessible from the global scope or overriding existing built-in functions. See example. Note that the first parameter passed to the validation function is the input value or 0/1 for checkboxes and radios. getModifiers Returns the object with all built-in modifiers of the current validator instance. This is useful for adding custom modifying functions which are not accessible from the global scope or overriding existing built-in modifiers. You can add your modifier function like this:

<script type="text/javascript"> $('#myform').data('bValidator').getModifiers().myMod = function(value){ // return changed value return 'newValue'; } </script> setScrollTo position in pixels Sets position in pixels for scrolling after validation.

Events

Example of using an event triggered by bValidator: <script type="text/javascript"> $('#myForm').on('beforeFormValidation.bvalidator', function () { // do something... }) </script> Event Description beforeFormValidation.bvalidator Triggered before a form validation starts. afterFormValidation.bvalidator Triggered after a form validation is finished. beforeFieldValidation.bvalidator Triggered before a field validation starts. afterFieldValidation.bvalidator Triggered after a field validation is finished. afterAjax.bvalidator Triggered after Ajax request. bValidator sets some values to the event object which you can access from within the event function: <script type="text/javascript"> $('#myForm').on('beforeFormValidation.bvalidator', function (event) { // bValidator instance event.bValidator.instance // validation result, true or false ('after' events only) event.bValidator.validationResult // array with error messages (afterFieldValidation only) event.bValidator.errorMessages // <form> which is validated event.target }) </script>

Examples

You can change the source code and play with each example by clicking on the 'Source' button. This page includes default Bootstrap 3 CSS and JavaScript. Note that some Bootstrap styles in the examples are modified for a simple HTML markup, so if you paste a form with Bootstrap HTML it will not look like you would expect. Click on the 'No styling' bellow the editor to disable customized styling and leave only default Bootstrap styles.

You can change the look of the validation messages in the examples by choosing the theme name from the useTheme dropdown in the main menu.

Basic example This is a basic example of using bValidator. Source No styling <form data-bvalidator-validate> <input data-bvalidator="email,required" placeholder="Enter an Email" type="text"> <button type="submit">Submit</button> </form> Custom messages You can set a validation message for the field with data-bvalidator-msg attribute: Source No styling <form data-bvalidator-validate> <label>Enter a number:</label> <input data-bvalidator="number,required" data-bvalidator-msg="Number please" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Source No styling <form data-bvalidator-validate data-bvalidator-option-validate-till-invalid="true"> <label>Enter something:</label> <input data-bvalidator="alpha,minlen[20],required" data-bvalidator-msg-minlen="Please enter more characters." type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> In the previous example validateTillInvalid option is used to show a message from one validation function at the time. Messages can also be set through options. This example shows how to set a validation message with options passed to bValidator constructor: Source No styling <script type="text/javascript"> var options = { messages: { en: { "ip4": "IP address must be in format x.x.x.x" } } }; // call bValidator constructor for the form $('#my-form-3').bValidator(options); </script> <form id="my-form-3"> <label>Enter IP4 adress:</label> <input data-bvalidator="ip4,required" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Validation function can return a message. If the validation function returns a string , it will be used as validation message. See also custom validation functions examples. Source No styling <script type="text/javascript"> function myValidationAction2(fieldValue){ // return true if field is valid // validation message return "Please enter something else"; } </script> <form data-bvalidator-validate> <label>Enter something:</label> <input data-bvalidator="myValidationAction2,required" type="text"> <button type="submit">Submit</button> </form> See more about messages here. Custom validation function If you want to make your own validation function, create a function that returns true for successful validation and put the function name in data-bvalidator attribute: Source No styling <script type="text/javascript"> function myValidationAction(fieldValue){ if(fieldValue == 'abc') return true; return false; } </script> <form data-bvalidator-validate> <label>Enter 'abc':</label> <input data-bvalidator="myValidationAction,required" data-bvalidator-msg="Please enter just 'abc'." type="text"> <button type="submit">Submit</button> </form> You can pass parameters to your validation function. First argument to a validation function is the value of the input field and other arguments (if any) are values stated in square brackets [] after the function name in data-bvalidator attribute. Source No styling <script type="text/javascript"> function myvalidator(number, devideBy){ number = parseFloat(number); if(number % parseInt(devideBy) == 0) return true; return false; } </script> <form data-bvalidator-validate> <label>Enter a number divisible by 3:</label> <input data-bvalidator="myvalidator[3],number,required" data-bvalidator-msg="Enter a number which is divisible by 3." type="text"> <label>Enter a number divisible by 4:</label> <input data-bvalidator="myvalidator[4],number,required" data-bvalidator-msg="Enter a number which is divisible by 4." type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> To submit the next form fill in both fields or leave them empty: Source No styling <script type="text/javascript"> function checkMyInputs(value, field){ if(field == '1'){ if(!value && $('#val_2').val()) return false; } else if(field == '2'){ if(!value && $('#val_1').val()) return false; } return true; } </script> <form data-bvalidator-validate> <label>Value 1:</label> <input id="val_1" data-bvalidator="checkMyInputs[1],valempty" data-bvalidator-msg="Please enter value in both fields or leave them empty" type="text"> <label>Value 2:</label> <input id="val_2" data-bvalidator="checkMyInputs[2],valempty" data-bvalidator-msg="Please enter value in both fields or leave them empty" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Password form: Source No styling <script type="text/javascript"> function passwordFormat(password){ regex = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/); // number, a-z, A-Z, min 8 chars if(regex.test(password)) return true; return false; } </script> <form data-bvalidator-validate> <label>Password</label> <input id="new_pass1" data-bvalidator="passwordFormat,required" data-bvalidator-msg="Min 8 characters including a number, letters a-z, A-Z" type="password"> <label>Confirm password</label> <input id="new_pass2" data-bvalidator="equal[new_pass1],required" data-bvalidator-msg-equal="Please enter the same password again" type="password"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> If your validation function is not accessible from global scope, you can add the validation function to a validator instance by using getValidators API function:

<script type="text/javascript"> $('#myform').data('bValidator').getValidators().myAction = function(value){ // check the value and return true if valid } </script> Or you can add your validation function to all instances of bValidator by adding the function to bValidator.validators object: <script type="text/javascript"> bValidator.validators.myAction = function(value){ // check the value and return true if valid } </script> Big form Source No styling <form data-bvalidator-validate> <label>Only digits:</label> <input data-bvalidator="digit,required" type="text"> <label>Number:</label> <input data-bvalidator="number,required" type="text"> <label>URL:</label> <input data-bvalidator="url,required" type="text"> <label>Pv4 address:</label> <input data-bvalidator="ip4,required" type="text"> <label>Choose one:</label> <input name="e" value="1" type="radio"> <input name="e" value="1" type="radio"> <input name="e" value="1" data-bvalidator="required" data-bvalidator-msg="Select one radio button" type="radio"> <br /> <label>Alphabetic characters only:</label> <input data-bvalidator="alpha,minlen[10],required" type="text"> <label>Alphanumeric characters only:</label> <input data-bvalidator="alphanum,minlen[10],required" type="text"> <label>Date in format dd.mm.yyyy:</label> <input data-bvalidator="date[dd.mm.yyyy],required" type="text"> <label>Value between 100 and 200:</label> <input data-bvalidator="between[100:200],required" type="text"> <label>Minimum length is 10 characters:</label> <input data-bvalidator="minlen[10],required" type="text"> <label>Maximum length is 10 characters:</label> <input data-bvalidator="maxlen[10],required" type="text"> <label>Enter between 10 and 20 characters:</label> <input data-bvalidator="rangelen[10:20],required" type="text"> <br /> <label>Select at least two checkboxes:</label> <input name="b[]" value="1" type="checkbox"> <input name="b[]" value="1" type="checkbox"> <input name="b[]" value="1" data-bvalidator="min[2],required" data-bvalidator-msg="Select at least two checkboxes" type="checkbox"> <br /> <label>Select .jpg, .png or .txt file:</label> <input data-bvalidator="extension[jpg:png:txt],required" data-bvalidator-msg="Please select file of type .jpg, .png or .txt" type="file"> <label>This checkbox is required:</label> <input data-bvalidator="required" type="checkbox"> <br /> <label>Minimum value is 10:</label> <input data-bvalidator="min[10],required" type="text"> <label>Select no more than 2 options:</label> <select size="5" multiple="multiple" class="form-control" data-bvalidator="max[2],required" data-bvalidator-msg="Select no more than 2 options"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> </select> <br /> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Checkboxes and radio buttons Source No styling <form data-bvalidator-validate> <label>Select two or none:</label> <input name="chk8[]" type="checkbox"> <input name="chk8[]" type="checkbox"> <input name="chk8[]" type="checkbox"> <input name="chk8[]" data-bvalidator="min[2],max[2]" data-bvalidator-msg="Select two or none checkboxes" type="checkbox"> <br /> <label>Select one:</label> <input name="radio8" value="1" type="radio"> <input name="radio8" value="2" type="radio"> <input name="radio8" value="3" type="radio"> <input name="radio8" value="4" data-bvalidator="required" data-bvalidator-msg="Select radio" type="radio"> <br /> <label>Select between three and five:</label><br /> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" data-bvalidator="between[3:5],required" data-bvalidator-msg="Number of selected checkboxes must be between 3 and 5" type="checkbox"><br> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"><br> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"> <input name="chk81[]" type="checkbox"><br /> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Checkboxes or radio buttons are grouped by giving the same name attribute to all elements in the group. data-bvalidator and data-bvalidator-msg attributes should be added to only one element in the group on which a validation message will be shown. Dynamic form Source No styling <form data-bvalidator-validate> <div id="container-for-new-elements"> </div> <div class="show-hide"> <label>Enter name:</label> <input data-bvalidator="alphanum,required" type="text"> </div> <label>Enter a number:</label> <input data-bvalidator="number,required" type="text"> <div class="show-hide"> <label>Enter Email:</label> <input data-bvalidator="required,email" type="text"> </div> <!-- this is here just as template for new elements --> <div id="new-element-template" style="display: none;"> <label>Enter a number:</label> <input data-bvalidator="number,required" type="text"> </div> <button type="button" onclick="$('#container-for-new-elements').append($('#new-element-template').html())">Add form element</button> <button type="button" onclick="$('.show-hide').toggle(400);">Show / Hide</button> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Inputs can be added to the form after bValidator is initialized. Note that hidden form elements are not validated by default. If you need to hide or show some elements, put them into a container element and then show or hide that container. Validation messages will not follow show/hide actions if you apply them only on the input element which is validated. That also depends on the theme that is used.

If you use validateOn option, after adding a new input to the form, call bindValidateOn API function to bind validateOn event. HTML5 form bValidator works nicely with HTML5 input types. See enableHtml5Attr option for supported attributes. You can also use data-bvalidator attributes with HTML5 markup. See also examples for bs3form theme. . Source No styling <form data-bvalidator-validate> <label>E-mail:</label> <input type="email" required> <br> <label>URL:</label> <input type="url" required> <br> <label>Number between 10 and 20:</label> <input type="number" min=10 max="20" required> <br> <label>5 - 10 characters:</label> <input type="text" maxlength="10" minlength="5" required> <br> <label>Numbers in format 123-456:</label> <input type="text" pattern="[0-9]{3}\-[0-9]{3}" required data-bvalidator-msg="Enter numbers in format 123-456-"> <br> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Container element doesn't have to be a <form> . You can trigger validation with JavaScript: Source No styling <script type="text/javascript"> $('#button006').on('click', function(){ if($('#input-container').data('bValidator').validate()) alert ('Is valid!'); }) </script> <div data-bvalidator-validate id="input-container"> <label>Only digits:</label> <input data-bvalidator="digit,required" type="text" > <button id="button006">Validate</button> </div> Any element can be validated like an <input> : Source No styling <script type="text/javascript"> function validateDiv(){ // do something here and return true or false return false } </script> <form data-bvalidator-validate> <div data-bvalidator="validateDiv,required" data-bvalidator-msg="Please check your calculation." class="bdocs-example-box"> Result: 1234 </div> <br /> <button type="submit">Submit</button> </form> More instances Enter letters and numbers in the field below: Source No styling <form data-bvalidator-validate="bvalidator,hint" data-hint-option-validate-on="keyup" data-hint-option-validate-on-submit="false" data-hint-theme="gray2"> <label>Minimum 15 characters:</label> <input data-bvalidator="minlen[15],required" data-hint="alpha" data-hint-msg="It would be nice if you enter only letters." type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> You can have more instances of bValidator on the same form. In the example above, there are two bValidator instances on the form. One named bvalidator (name for the default instance) and another named hint . Names are stated in data-bvalidator-validate attribute. Each instance has its own options. In this example hint instance is configured not to submit the form, to use gray2 theme and to validate on keyup event. For hint instance options are set with data-hint- attributes in the same way as with data-bvalidator- attributes for the default instance. Similar example but defined with JavaScript: Source No styling <form id="formInstancesExample"> <label>Enter username:</label> <input data-bvalidator="minlen[10],required" data-hint="email" data-hint-msg="You can use your email as username." type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> <script type="text/javascript"> // options for hint instance var optionsHints = { validateOn: 'keyup', validateOnSubmit: false, useTheme: 'gray2' }; $('#formInstancesExample').bValidator(); // default instance $('#formInstancesExample').bValidator(optionsHints, 'hint'); // hint instance </script> Just displaying messages Source No styling <script type="text/javascript"> $(document).ready(function () { $('#justMessages').bValidator(); }); // elements to show messages on var $elements = $('#justMessages input, #justMessages span'); // shows messages function showMessges(){ $('#justMessages').data('bValidator').showMsg($elements, 'Hi there'); } // hides messages function hideMessges(){ $('#justMessages').data('bValidator').removeMsg($elements); } </script> <div id="justMessages" class="form-horizontal"> <div class="form-group"> <div class="col-md-4"> <input data-bvalidator-theme="gray2" type="text"> </div> <div class="col-md-4"> <input data-bvalidator-theme="postit" type="text"> </div> <div class="col-md-4"> <span class="bg-success"><span></span> </div> </div> <button type="button" onclick="showMessges()">Show messages</button> <button type="button" onclick="hideMessges()">Hide messages</button> </div> In this example no validation is done, only messages are displayed. Messages can be displayed on any element on the page, it doesn't have to be an input and it doesn't have to be inside the container element on which bValidator is bound. Forcing validation result Sometimes after bValidator is initialized you may want to disable validation for a <form> or an <input> or you want to force them invalid. You can do it by adding data-bvalidator-return attribute with value true or false . Put the attribute on the <form> if you want to force validation result for all inputs inside the form. Source No styling <form data-bvalidator-validate> <label>Number:</label> <input data-bvalidator="number,required" data-bvalidator-return="true" type="text"> <label>Number:</label> <input data-bvalidator="number,required" data-bvalidator-return="false" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> You can also force validation result for all fields inside the <form> with forceValidationResult option: $('form').data('bValidator').getOptions().forceValidationResult = true; Modifiers Modifiers are functions which purpose is to change the input value before validation. For example, to strip trailing/leading whitespace. Modifiers are called before validation functions. Modifying function are listed in data-bvalidator-modifier attribute by default, the same as validation functions are listed data-bvalidator attribute. For some validation functions trim modifier is called by default (see autoModifiers option). Source No styling <script type="text/javascript"> function myDigitsModifier(oldValue){ return oldValue.replace(/[^0-9\.]/g, "") // leave only digits } function myURLModifier(oldValue){ if(oldValue.substring(0, 4) != 'http') return 'http://' + oldValue } </script> <form data-bvalidator-validate> <label>E-mail:</label> <input type="text" data-bvalidator="email,required"> <p class="help-block">(put whitespaces at the beginning or the end)</p> <label>Only digits:</label> <input type="text" data-bvalidator="digit,required" data-bvalidator-modifier="myDigitsModifier"> <p class="help-block">(try to enter some letters)</p> <label>URL:</label> <input type="text" data-bvalidator="url,required" data-bvalidator-modifier="myURLModifier"> <p class="help-block">(try to enter without http://)</p> <label>Enter some word:</label> <input type="text" data-bvalidator-modifier="trim"> <p class="help-block">(put whitespaces at the beginning or the end)</p> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> In this example, trim modifier is automatically called on the first field because email function is mentioned by default in autoModifiers option.

On the second field, custom modifier will delete all but digits.

The third field modifier will add 'http://' if you enter URL without it.

The fourth field has modifying function only, no validation at all. You can use only modifier on the field without data-bvalidator attribute and validation. Note that the first argument of a modifying function is the value of the input. Other arguments (if any) are values stated in square brackets [] after the function name in data-bvalidator-modifier attribute (same as for custom validation functions). Modifying function should return a new value for the input field. If nothing ( undefined ) is returned, the input value will not be changed. Server side validation This field is validated on the server side with ajax function: Source No styling <form data-bvalidator-option-ajax-url="lib/ajax-response/response-notok.txt" data-bvalidator-validate> <input data-bvalidator="ajax,required" data-bvalidator-msg="Invalid username." name="username" placeholder="Username" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> The data-bvalidator-option-ajax-url attribute on the <form> contains URL to which the request is sent. By default, bValidator will make asynchronous HTTP (Ajax) request sending values of the inputs that are validated. If the field is valid, the response from the server should be a string defined by ajaxValid option ("ok" by default). The server can also return a JSON string with results for each validated field. In the next example both fields are validated on the client and also on the server: Source No styling <form data-bvalidator-option-ajax-url="lib/ajax-response/response-json-notok.txt" data-bvalidator-validate> <label>Enter username:</label> <input data-bvalidator="email,ajax,required" data-bvalidator-msg-ajax="Username is already taken." name="username" type="text"> <label>Enter number:</label> <input data-bvalidator="digit,ajax,required" data-bvalidator-msg-ajax="The number is not in the database." name="number" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Server validation won't be invoked if the value is invalid by some other validation function ( email in this example) or if the value is not changed since the last check. JSON string returned from the server should be in format: {"inputName1":"ok", "inputName2":"ok"} For the fields that are valid, JSON property should have "ok" value by default. JSON properties for the fields that are not valid can have any other value or don't have to be included in the response. If all fields are valid only "ok" string can be returned from the server. Validation message for ajax function can be set by data-bvalidator-msg-ajax attribute (see more about messages). Validator will make Ajax request only for the fields which need validation and expect response only for those fields. In this examples, all fields are always in JSON response, but that's because a static text file and not a real validation script is on the server side. You can also return validation messages from the server. In the next example, all fields are validated on the server and all messages come from the server: Source No styling <form data-bvalidator-option-ajax-response-msg="true" data-bvalidator-option-ajax-url="lib/ajax-response/response-json3.txt" data-bvalidator-validate> <input data-bvalidator="ajax,valempty" name="value1" placeholder="value 1" type="text"> <input data-bvalidator="ajax,valempty" name="value2" placeholder="value 2" type="text"> <input data-bvalidator="ajax,valempty" name="value3" placeholder="value 3" type="text"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> Set ajaxResponseMsg option to true to show messages from the server response. valempty function is used here instead of required , because required will show the validation message that the field is required and skip server validation. This way the field is always validated on the server side, even if empty.

Themes

Themes define the look of validation messages. To use a theme you need to include .css and .js files for the theme. To set the theme for all fields in the form, set the theme name with data-bvalidator-theme attribute on the <form> : <form data-bvalidator-theme="gray3" data-bvalidator-validate> <input type="text" data-bvalidator="alphanum,required"/> </form> That is the same as setting useTheme option with data-bvalidator-option-use-theme attribute. To change the theme only for the specific input field, put data-bvalidator-theme attribute on the <input> : <form data-bvalidator-validate> <input type="text" data-bvalidator="alphanum,required" data-bvalidator-theme="gray3"/> </form> With JavaScript, you can set the default theme by changing useTheme option. For example, you can set the default theme depending on the screen width and for small-screen devices choose more adapted theme: <script type="text/javascript"> if ($(window).width() < 760) bValidator.defaultOptions.useTheme = 'insert'; else bValidator.defaultOptions.useTheme = 'gray'; </script> Theme examples and options: Options for themes can be set by data-bvalidator-theme-optionName attribute or by JavaScript. You can set data-bvalidator-theme-optionName attribute on the <form> element to change the option for all the fields in the form: <form data-bvalidator-theme-offset="-20,0" data-bvalidator-validate> <input type="text" data-bvalidator="alphanum,required"/> </form> If you put data-bvalidator-theme-optionName attribute on the <input> , the option will be set only for that field: <form data-bvalidator-validate> <input type="text" data-bvalidator-theme-offset="-20,0" data-bvalidator="alphanum,required"/> </form> Theme options can also be set by changing default options: <script type="text/javascript"> bValidator.defaultOptions.themes.gray3.offset = '-20,0'; bValidator.defaultOptions.themes.gray3.showClose = false; </script> Or by passing object with options to bValidator constructor function: <script type="text/javascript"> var options = { themes: { 'gray3': { showClose: false } } }; $('#myform').bValidator(options); </script> gray <form data-bvalidator-theme="gray" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> Options for gray theme: Option Default Description offset "-23,-4" Fine tunes the message position. showClose true If true , messages will have a close icon. msgShowSpeed "normal" Message's fade-in speed. Values can be fast , normal , slow or number of milliseconds. position "right,top" Zero position for the message. First value is for the horizontal position ( left , center , right ), second value is for the vertical position ( top , center , bottom ). invalidClass "bvalidator-gray-invalid" CSS class that will be added to the field if invalid. validClass "" CSS class that will be added to the field if valid. template "<div class="bvalidator-gray-tooltip bvalidator-gray-tooltip-noclose"><div class="bvalidator-gray-arrow"></div><div class="bvalidator-gray-msg">{message}</div></div>" Template for the message without the close icon. templateClose "<div class="bvalidator-gray-tooltip"><div class="bvalidator-gray-arrow"></div><div class="bvalidator-gray-msg">{message}</div><div class="bvalidator-gray-close">×</div></div>" Template for the message with the close icon. Files to include for gray theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/gray/gray.js"></script> <link href="themes/gray/gray.css" rel="stylesheet" /> bs3form This theme uses Bootstrap's form validation styles and is designed for pages built with Bootstrap 3. For this theme to work correctly you have to make forms with Bootstrap markup. It is important to place form-group and control-label classes correctly. See Bootstrap documentation for details. <form data-bvalidator-validate data-bvalidator-theme="bs3form"> <div class="form-group"> <label class="control-label">Email address</label> <input type="email" class="form-control" placeholder="Email" required> </div> <div class="form-group"> <label class="sr-only">Amount</label> <div class="input-group"> <div class="input-group-addon"> $ </div> <input type="number" required class="form-control" placeholder="Amount"> <div class="input-group-addon"> .00 </div> </div> </div> <div class="form-group"> <div class="checkbox"> <label> <input type="checkbox" required> Check me out </label> </div> </div> <div class="form-group"> <select class="form-control" required> <option value="">Choose something</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> </div> <div class="form-group"> <label class="control-label">Group of checkboxes</label> <div> <label class="checkbox-inline"> <input data-bvalidator-msg="Number of selected checkboxes must be between 3 and 5" data-bvalidator="between[3:5],required" type="checkbox" name=chk883[]> 1 </label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 2</label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 3</label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 4</label> <br> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 5</label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 6</label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 7</label> <label class="checkbox-inline"> <input type="checkbox" name=chk883[]> 8</label> </div> </div> <div class="form-group"> <label class="control-label">Radios</label> <div> <label class="radio-inline"> <input type="radio" name="radio9986" value="1" required data-bvalidator-msg="Please select something"> one </label> <label class="radio-inline"> <input type="radio" name="radio9986" value="2"> two </label> <label class="radio-inline"> <input type="radio" name="radio9986" value="3"> three </label> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-primary ">Reset</button> </form> With horizontal forms use the helper class bvalidator-bs3form-msg to mark the element into which to append the validation message. By default, the message is appended to form-group element. <form data-bvalidator-validate data-bvalidator-theme="bs3form" class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">Email</label> <div class="col-sm-10 bvalidator-bs3form-msg"> <div class="input-group"> <span class="input-group-addon">@</span> <input required type="email" class="form-control" placeholder="Email"> </div> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Select</label> <div class="col-sm-10 bvalidator-bs3form-msg"> <select class="form-control" required> <option value="">Choose something</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Choose</label> <div class="col-sm-10 bvalidator-bs3form-msg"> <label class="radio-inline"> <input type="radio" name="radio99862" value="1" required data-bvalidator-msg="Please select something"> one </label> <label class="radio-inline"> <input type="radio" name="radio99862" value="2"> two </label> <label class="radio-inline"> <input type="radio" name="radio99862" value="3"> three </label> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-primary ">Reset</button> </div> </div> </form> Next example is Inline form. showMessages option is set to false to not show the messages: <form data-bvalidator-validate data-bvalidator-theme="bs3form" data-bvalidator-theme-show-messages="false" class="form-inline"> <div class="form-group"> <label class="control-label">Name</label> <input required type="text" class="form-control"> </div> <div class="form-group"> <label class="control-label">Address</label> <input required type="text" class="form-control"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-primary ">Reset</button> </div> </form> Options for bs3form theme: Option Default Description template "<div class="help-block">{message}</div>" Template for a validation message. If showMessages option is set to false you can change the template to use sr-only class for assistive technologies. formGroupInvalidClass "has-error" CSS class that will be added to the formGroup element if invalid. formGroupValidClass "" CSS class that will be added to the formGroup element if valid. has-success is a default Bootstrap class for this. showMessages true If true messages will be shown. formGroup ".form-group" jQuery selector for the element with form-group class. If it doesn't start with # , search with jQuery's .closest() is used. msgParent ".bvalidator-bs3form-msg" jQuery selector for the element to append a validation message into. If it doesn't start with # , search with jQuery's .closest() is used. Files to include for bs3form theme: <script src="themes/presenters/bs3form.min.js"></script> <script src="themes/bs3/bs3form/bs3form.js"></script> bs3popover This theme uses Bootstrap Popover plugin to show messages. You have to include bootstrap js and css for this theme to work. <form id="wert" data-bvalidator-theme="bs3popover" data-bvalidator-return="false" class="text-center"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="top"> <br /> <input data-bvalidator="" type="text"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="left"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="bottom"> <br /> <br /> </form> Options for bs3popover theme: Option Default Description placement "right" How to position the popover. top | bottom | left | right | auto . showClose true If true , popover will have the close icon. content "<div class="bvalidator-bs3popover-msg bvalidator-bs3popover-msg-noclose">{message}</div>" Template for the popover content without the close icon. contentClose "<div class="bvalidator-bs3popover-msg">{message}</div><div class="bvalidator-bs3popover-close"><button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div>" Template for the popover content with the close icon. tooltipOptions {

html: 'true',

template: '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"></div></div>',

viewport: null,

trigger: 'manual'

} Popover options. See Bootstrap documentation for all options. Files to include for bs3popover theme: <script src="themes/presenters/bs3popover-tooltip.min.js"></script> <script src="themes/bs3/bs3popover/bs3popover.js"></script> <link href="themes/bs3/bs3popover/bs3popover.css" rel="stylesheet" /> bs3tooltip This theme is similar to bs3popover theme but it uses Tooltip plugin to display messages. You have to include bootstrap js and css for this theme to work. <form data-bvalidator-theme="bs3tooltip" data-bvalidator-return="false" class="text-center"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="top"> <br /> <input data-bvalidator="" type="text"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="left"> <br /> <input data-bvalidator="" type="text" data-bvalidator-theme-placement="bottom"> <br /> <br /> </form> Options for bs3tooltip theme: Option Default Description placement "right" How to position the tooltip. top | bottom | left | right | auto . showClose true If true , tooltip will have the close icon. content "<div class="bvalidator-bs3tooltip-msg bvalidator-bs3tooltip-msg-noclose">{message}</div>" Template for the tooltip content without the close icon. contentClose "<div class="bvalidator-bs3tooltip-msg">{message}</div><div class="bvalidator-bs3tooltip-close"><button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div>" Template for the tooltip content with the close icon. tooltipOptions {

html: 'true',

viewport: null,

trigger: 'manual',

sanitize : false

} Tooltip options. See Bootstrap documentation for all options. Files to include for bs3tooltip theme: <script src="themes/presenters/bs3popover-tooltip.min.js"></script> <script src="themes/bs3/bs3tooltip/bs3tooltip.js"></script> <link href="themes/bs3/bs3tooltip/bs3tooltip.css" rel="stylesheet" /> insert This is a simple theme which just inserts a message before or after the input which is checked. <form data-bvalidator-theme="insert" data-bvalidator-return="false"> <input data-bvalidator="" type="text" > </form> You can easily change message styles or template by setting options: <form data-bvalidator-theme="insert" data-bvalidator-return="false"> <input data-bvalidator="" type="text" data-bvalidator-theme-msg-class="text-danger" data-bvalidator-theme-invalid-class="bdocs-example-back-orange"> </form> Options for insert theme: Option Default Description placement "after" Where to put a message, after or before . invalidClass "bvalidator-insert-invalid" CSS class that will be added to the field if invalid. validClass "" CSS class that will be added to the field if valid. msgClass "bvalidator-insert-msg" This value will replace {msgClass} in template option. template "<div class="{msgClass}">{message}</div>" Template for a validation message. Files to include for insert theme: <script src="themes/presenters/insert.min.js"></script> <script src="themes/insert/insert.js"></script> <link href="themes/insert/insert.css" rel="stylesheet" /> group This theme puts all validation messages into one container. <form data-bvalidator-theme="group" data-bvalidator-return="false"> <label>Enter something:</label> <input data-bvalidator="" data-bvalidator-msg="Please enter something." type="text"> <label>Enter something else:</label> <input data-bvalidator="" data-bvalidator-msg="Please enter something else." type="text"> </form> Options for group theme: Option Default Description msgClass "bvalidator-group-msg" CSS class for validation messages container. invalidClass "bvalidator-group-invalid" CSS class that will be added to the field if invalid. validClass "" CSS class that will be added to the field if valid. makeMsgContainer null Function that returns the element into which all messages will be prepend. It is called with two arguments: $form and $input . If null , messages are prepend into the <form> . Files to include for group theme: <script src="themes/presenters/group.min.js"></script> <script src="themes/group/group.js"></script> <link href="themes/group/group.css" rel="stylesheet" /> gray2 <form data-bvalidator-theme="gray2" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for gray2 theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/gray2/gray2.js"></script> <link href="themes/gray2/gray2.css" rel="stylesheet" /> gray3 <form data-bvalidator-theme="gray3" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for gray3 theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/gray3/gray3.js"></script> <link href="themes/gray3/gray3.css" rel="stylesheet" /> gray4 <form data-bvalidator-theme="gray4" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for gray4 theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/gray4/gray4.js"></script> <link href="themes/gray4/gray4.css" rel="stylesheet" /> orange <form data-bvalidator-theme="orange" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for orange theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/orange/orange.js"></script> <link href="themes/orange/orange.css" rel="stylesheet" /> postit <form data-bvalidator-theme="postit" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for postit theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/postit/postit.js"></script> <link href="themes/postit/postit.css" rel="stylesheet" /> red <form data-bvalidator-theme="red" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for red theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/red/red.js"></script> <link href="themes/red/red.css" rel="stylesheet" /> bslikerc This theme looks like Bootstrap popover with right placement, but it doesn't depend on Bootstrap as bs3popover theme does. <form data-bvalidator-theme="bslikerc" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme has the same options as the gray theme, see the theme .js file for default values. Files to include for bslikerc theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/bslikerc/bslikerc.js"></script> <link href="themes/bslikerc/bslikerc.css" rel="stylesheet" /> bslikert <form data-bvalidator-theme="bslikert" data-bvalidator-return="false"> <input data-bvalidator="" type="text"> </form> This theme looks similar to Bootstrap popover, but it doesn't depend on Bootstrap as bs3popover theme does and has the same options as the gray theme. See the theme .js file for default options values. Files to include for bslikert theme: <script src="themes/presenters/default.min.js"></script> <script src="themes/bslikert/bslikert.js"></script> <link href="themes/bslikert/bslikert.css" rel="stylesheet" />

Licence

bValidator is licensed under MIT license so it is free and you can use it without restrictions.