Form validation made easy

jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. Even though this plugin has a wide range of validation functions it's designed to require as little bandwidth as possible. This is achieved by grouping together validation functions in "modules", making it possible for the programmer to load only those functions that's needed to validate a particular form.

This plugin is available through cdnjs, bower and github.

Basic example

User name (4 characters minimum, only alphanumeric characters):

Year (yyyy-mm-dd):

Website:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate(); </script> ...

Support for HTML5

html5

By adding the module html5 to the module declaration you will be able to validate user input using the native attributes, in accordance to the HTML5 specification.

Click here to read more.

Form demo

The following form contains some typical validators needed in a registration form. This jQuery plugin has support for a lot more validation functions, you find them all in the menu to the right.

Read the setup guide if you want to know which configuration options that's available when setting up the validation.

Here you can read more about styling of the form and error dialogs.

100 chars left
I agree to the terms of service

E-mail

User name

Password

Repeat password

Birth date

Country

Profile image

User Presentation (100 characters left)

I agree to the terms of service

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'location, date, security, file', onModulesLoaded : function() { $('#country').suggestCountry(); } }); // Restrict presentation length $('#presentation').restrictLength( $('#pres-max-length') ); </script> ...

Default validators

The default features of this plugin comes out the box which means that you don't need to load any module to use them. Here you can try out a complete form with all default validators present.


Answer length (required)














This plugin also supports the attributes "required" and "maxlength" by using the Html5 module.

Numbers





















                

You can also define the decimal separator when initializing the validation.

Average points

....
</form> <script> $.validate({ decimalSeparator : ',' }); </script>

Inputs of type "number" will also become validated by loading the html5 module.

E-mail


Inputs of type "email" will also become validated by loading the html5 module.

URL:s


Inputs of type "url" will also become validated by loading the html5 module.

Date






                

See the date module for further validators.

Alphanumeric






If you want to allow any kind of letters (not only A-Z) you're looking for the letternumeric validator.

Checkboxes Group

Validate qty of checkboxes in a group (same name) have been checked, using min, max or range. Only the first checkbox element in the group needs to have the validation attributes added.







If your checkboxes group is generated by a server-side script and you don't want to add the validation attributes to each input element, you can use this javascript snippet before calling the validatorLoad() function

<!-- Add validation attributes to first input element in
 checkboxes group, before loading validator -->
<script>
$("[name='newsletters[]']:eq(0)")
    .valAttr('','validate_checkbox_group')
    .valAttr('qty','1-2')
    .valAttr('error-msg','chose 1, max 2');
</script>

Regexp



This plugin also supports the attribute "pattern" by using the Html5 module.

Character count down

History (50 characters left)

<script> $('#area').restrictLength($('#maxlength')); </script>

Make validation optional







Display help text

It is possible to display help information beside each input. The text will fade in when the input gets focus on and fade out when the input looses focus. The container for the help text will have the class form-help. If you don't want this feature you can read the setup guide on how to disable it.

Why not?

...

Validate inputs when blurred

By default each input will become validated immediately when the input looses focus. If you don't want this feature you can read the setup guide on how to disable it.

Input suggestions

There are two ways you can give suggestions to the user while the user types.

1) Using attribute data-suggestions

What's your favorite color?

...
</form>
2) Using $.formUtils.suggest()
<script>
    var largeArray = [];
    largeArray.push('Something');
    largeArray.push('Something else');
    ...

    $.formUtils.suggest( $('#the-input'), largeArray );
</script>

This plugin also supports the data-list element by using the Html5 module.


Example form

Here you can read more about styling of the form and error dialogs.

100 chars left

E-mail

URL

Only allows alphanumeric characters and hyphen and underscore

Only lowercase letters a-z (regexp)

Minimum 5 chars

Maximum 5 chars

Between 3-5 chars

What's your favorite color?

Validate e-mail but only if an answer is given

Validate e-mail but only if checkbox is checked

Restrict length 100 chars left

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate(); $('#my-textarea').restrictLength( $('#max-length-element') ); </script> ...

Read the setup guide if you want to know which configuration options that's available when setting up the validation.

Security validators

This module contains validators commonly used in registration forms. Here you can try an example form with all the security validators in action.

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
    $.validate({
        modules : 'security'
    });
</script>

Password confirmation

This validator can be used to validate that the values of two inputs are the same. The first input should have a name suffixed with _confirmation and the second should have the same name but without the suffix.

Password (at least 8 characters) Confirm password

As of version 2.2.1 you can use the attribute data-validation-confirm to define which other input that the second input should confirm.

E-mail Repeat e-mail

Password strength

Use this validator to make sure that your user has a strong enough password. Set attribute data-validation-strength to 1, 2 or 3 depending on how strong password you require.

If you want the strength of the password to be displayed while the user types you call displayPasswordStrength() in the end of the form.

Password:

...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'security', onModulesLoaded : function() { var optionalConfig = { fontSize: '12pt', padding: '4px', bad : 'Very bad', weak : 'Weak', good : 'Good', strong : 'Strong' }; $('input[name="pass"]').displayPasswordStrength(optionalConfig); } }); </script>

Validate on server side

By using this validator you can validate the value given by the user on the server before the form gets submitted. The validation function will send a POST request to the URL declared in data-validation-url. The argument posted to the URL will have the same name as the input being validated.

The form will get the class validating-server-side while the server is being requested.

The response from the validation script must be a JSON formatted object, containing the properties "valid" and "message".

{
    "valid" : true|false,
    "message" : "String with text that should be displayed as error message"
}
Form

User name:

...
/validate-input.php
<?php
$response = array(
    'valid' => false,
    'message' => 'Post argument "user" is missing.'
);

if( isset($_POST['user']) ) {
    $userRepo = new UserRepository( DataStorage::instance() );
    $user = $userRepo->loadUser( $_POST['user'] );

    if( $user ) {
        // User name is registered on another account
        $response = array('valid' => false, 'message' => 'This user name is already registered.');
    } else {
        // User name is available
        $response = array('valid' => true);
    }
}
echo json_encode($response);

Modifying the server request

The parameter containing the input value, sent to the server, will by default have the same name as the input. You can however set your own parameter name by using the attribute data-validation-param-name. You can also send along other parameters to the server by using the attribute data-validation-req-params.

<?php
  $json = json_encode(array('user'=>$user->get('ID')));
?>
<p>
  <strong>E-mail:</strong>
  <input type="email" name="check-email" data-validation="server"
              data-validation-url="/validate-form-input.php"
              data-validation-param-name="email"
              data-validation-req-params="<?php echo $json ?>" />
</p>

Credit card validation

This validator makes it possible to validate any of the credit cards VISA, Mastercard, Diners club, Maestro, CJB, Discover and American express

<-- Accept credit card number from Visa, Mastercard and American Express -->

Credit card number

Security code (cvv)

You can also let the user choose a credit card and programmatically change the allowed credit card on the input of the card number.

Credit card

Credit card number

...
<script> $.validate({ modules : 'security', onModulesLoaded : function() { // Bind card type to card number validator $('#credit-card').on('change', function() { var card = $(this).val(); $('input[name="creditcard_num"]').attr('data-validation-allowing', card); }); } }); </script>

Simple captcha

<?php
session_start();
if( isset($_POST['captcha']) && isset($_SESSION['captcha'])) {
    if( $_POST['captcha'] != ($_SESSION['captcha'][0]+$_SESSION['captcha'][1]) ) {
        die('Invalid captcha answer');  // client does not have javascript enabled
    }
    // process form data
    ...
}
$_SESSION['captcha'] = array( mt_rand(0,9), mt_rand(1, 9) );
?>
<form action="">
    <p>
        What is the sum of <?=$_SESSION['captcha'][0]?> + <?=$_SESSION['captcha'][1]?>?
        (security question)
        <input name="captcha" data-validation="spamcheck"
                    data-validation-captcha="<?=( $_SESSION['capthca'][0] + $_SESSION['captcha'][1] )?>"/>
    </p>
    <p><input type="submit" /></p>
</form>
...

Letters and numbers

By using the validator letternumeric you can validate that given input value only contains letters and/or numbers. This validator allows any type of character in contrast to the alphanumeric validator, which only allows letters A-Z.







Example form

Here you can read more about styling of the form and error dialogs.

<html>
<head>
<style type="text/css">
    /* Add ajax preloader when server is being requested */
    .validating_server_side input.server {
        background: url(img/ajax-preloader.gif) no-repeat center right;
        opacity: 0.6
    }
</style>
...

User name

Password

Confirm password

Code (validated on server side)

Credit card

Credit card number

CVV

What is the sum of 3 + 4?

Only letters, numbers and spaces allowed

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'security', onModulesLoaded : function() { // Show strength of password $('input[name="pass_confirmation"]').displayPasswordStrength(); // Bind card type to card number validator $('#card').on('change', function() { var card = $(this).val(); $('input[name="ccard_num"]').attr('data-validation-allowing', card); }); } }); </script> ...

Date validators

This module contains validators needed when validating dates and time. Here you can try an example form with all the date validators in action.

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
$.validate({
    modules : 'date'
});
</script>

Birthdate

This validator is the same as the default date validator except that it only allows past dates and dates that is not older than 120 years.






                

Time




Example form

Here you can read more about styling of the form and error dialogs.

Birth date

Time

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'date' }); </script> ...

File validators

This module contains validators needed when validating file uploads. All the validators in this module, except for extension, requires that the browser has implemented the File API (http://caniuse.com/#feat=fileapi).

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
$.validate({
    modules : 'file'
});
</script>

File size

This validation is only supported by Internet Explorer 10, Mozilla FireFox v >= 3.6 and any of the later versions of webkit based browsers.






                

File type

This validation will fall back on checking the file extension in older browsers. In modern browsers the validation will check that any of the extensions in data-validation-allowing exists in the mime type declaration of the file. This means that data-validation-allowing="pdf" will work in both modern browsers (checking against "application/pdf") and older browsers (checking the file extension ".pdf").






Validating multiple files (with separate error messages depending on failed validation):

<input type="file" multiple="multiple" name="images"
    data-validation="length mime size"
    data-validation-length="min2"
    data-validation-allowing="jpg, png, gif"
    data-validation-max-size="512kb"
    data-validation-error-msg-size="You can not upload images larger than 512kb"
    data-validation-error-msg-mime="You can only upload images"
    data-validation-error-msg-length="You have to upload at least two images"
    />

Image dimension and ratio

Use the validator dimension to check the dimension of an image (jpg, gif or png).















Use the attribute data-validation-ratio to validate that the uploaded image has a certain ratio








Location validators

This module contains validators needed when validating geographical data. Here you can try an example form with all the location validators in action.

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
$.validate({
    modules : 'location'
});
</script>

Country



                

State (US)



                

Longitude, Latitude



                

Suggest country/state

By using this function you'll make it easier for your visitor to input a country or state.

...

Which country are you from?

Which state do you live in?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'location', onModulesLoaded : function() { $('input[name="user_country"]').suggestCountry(); $('input[name="user_home_state"]').suggestState(); } }); </script>

Example form

Here you can read more about styling of the form and error dialogs.

Country

State

Longitude, Latitude

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'location', onModulesLoaded : function() { $('input[name="state"]').suggestCountry(); $('input[name="country"]').suggestState(); } }); </script> ...

Swedish validators

This module contains validators that comes in handy on Swedish websites. Here you can try an example form with all the Swedish validators in action.

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
$.validate({
    modules : 'sweden'
});
</script>

Validate phone number






                

Validate social security number






                

It's also possible to validate that the user has entered a valid gender based on the social security number.

Gender:

Social security number

...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'sweden', onValidate : function( $form ) { // We have a valid ssn if( $form.find('input[name="ssn"]').hasClass('valid') ) { var $genderList = $form.find('select[name="gender"]'); if( $genderList.val() != window.ssnGender ) { // Return info about failed validation return { element : $genderList, message : 'You gave an incorrect gender according to your security number' } } } } }); </script>

Validate municipality (kommun)

    

Validate county (län)

    

Suggest kommun/län

By using these functions you'll make it easier for your visitors to input a Swedish county or municipality.

...

Which county are you living in?

Which municipality are you living in?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'sweden', onModulesLoaded : function() { $('input[name="county"]').suggestSwedishCounty(); $('input[name="municipality"]').suggestSwedishMunicipality(); } }); </script>

Example form

Here you can read more about styling of the form and error dialogs.

Phone number

Mobile phone

Social security number

Län

Kommun

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'sweden', onModulesLoaded : function() { $('input[name="lan"]').suggestSwedishCounty(); $('input[name="kommun"]').suggestSwedishMunicipality(); } }); </script> ...

UK Validators

This module contains validators that comes in handy on brittish websites.

The following code shows you how to load the module.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
    $.validate({
        modules : 'uk'
    });
</script>

VAT

    

Setup and configuration

In this section we will go through the different configuration options you can use
when setting up the validation.


Setup

// Setup form validation on all forms
$.validate();
// Setup form validation only on the form having id "registration"
$.validate({
    form : '#registration'
});
// Setup form validation on the forms that has id #registration and #login
$.validate({
    form : '#registration, #login'
});

If wanting to refresh the validation setup all you have to do is to call $.validate() once more. To remove error messages and error styling you must call the native function reset() on the form element.

<script>
// Reset form using jQuery
$('#container form').get(0).reset();
</script>

Loading modules

Use the property modules to declare which modules you want to load. The property should contain a comma separated string with module names.

Use the property onModulesLoaded to declare a function that should be called after that the modules has loaded.

$.validate({
    modules : 'date, security',
    onModulesLoaded : function() {
        alert('All modules loaded!');
    }
});

Here you can read more about how to create your own modules.

Validation callbacks

There are four different callbacks you can declare when setting up the validation. There are also two types of events triggered on elements when they get validated.

  • onError – Called when the user submits the form and one or more inputs has an invalid value.
  • onSuccess – Called when the user submits the form and no input with an invalid value can be found.
  • onValidate – Called when the user submits the form and all inputs have become validated. This callback is called before onError/onSuccess. You can add error messages from this callback by returning an object containing the property "element" (referring to the input element having an invalid value) and "message". You can also return an array with error objects if you want to add several error messages. The validation procedure will go on as normally if the callback function doesn't return anything.
  • onElementValidate – Called after that an element have become validated.
  • beforeValidation – jQuery event triggered on elements right before they become validated.
  • validation – jQuery event triggered on elements after they have been validated.
    $.validate({
        form : '#registration-form',
        modules : 'security',
        onError : function($form) {
            alert('Validation of form '+$form.attr('id')+' failed!');
        },
        onSuccess : function($form) {
            alert('The form '+$form.attr('id')+' is valid!');
            return false; // Will stop the submission of the form
        },
        onValidate : function() {
            return {
                element : $('#some-input'),
                message : 'This input has an invalid value for some reason'
            }
        },
        onElementValidate : function(valid, $el, $form, errorMess) {
            console.log('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
        }
    });

    // Validation event listeners
    $('input')
        .on('beforeValidation', function() {
            console.log('Input "'+this.name+'" is about to become validated');
        })
        .on('validation', function(evt, valid) {
            console.log('Input "'+this.name+'" is ' + (valid ? 'VALID' : 'NOT VALID'));
        });

Styling

This plugin is compatible with twitter bootstrap 3.x out of the box. The classes mentioned below is in addition to classes used by twitter bootstrap.

An input that has a valid value will get the class valid, if the value is invalid the input will get the class error. The error messages is placed in a span element with the class form-error. Both of these class names can be configured using the properties errorElementClass and errorMessageClass.

An input with an invalid value will automatically get a red border color. You can use the setup function if you want to change the border color to something else, set the property to an empty string if you don't want the border color to change when the input has an invalid value.

The valid class will only be applied on inputs that is validated. Set the configuration option addValidClassOnAll to true if you also want the inputs not having any validation rules to get the class valid when the form gets submitted.

$.validate({
    borderColorOnError : '#FFF',
    addValidClassOnAll : true
});

A typical markup for a form using twitter bootstrap has each input in a div element with the class form-group and a label element with the class control-label containing the description of the input. The input element should have the class form-control.

<form action="..." role="form">
    <div class="form-group">
        <label class="control-label" for="the-input">Input description</label>
        <input type="text" id="the-input" class="form-control" data-validation="required" />
    </div>
    ...

Default theme

You can use the default CSS-theme if you want the styling of the validation elements (error dialogs, icons etc) to look exactly as they do here on formvalidator.net. Add the following stylesheet declaration in the header of your document.

<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/default-theme.min.css"
        rel="stylesheet" type="text/css" />

Disabling features

You can disable some of the features of this plugin by using the following configuration options.

  • validateOnBlur – Set this property to false if you only want the form to become validated when the user clicks on the submit button.
  • showHelpOnFocus – Set this property to false if you don't want the plugin to search through the form for help information.
  • addSuggestions – Set this property to false if you don't want the plugin to search through the form for input suggestions.
$.validate({
    validateOnBlur : false,
    showHelpOnFocus : false,
    addSuggestions : false
});

HTML5 support

As of version 2.2 you can use this plugin as a fallback solution for the validation attributes in the HTML5 specification. Add the module html5 to the module declaration and you can use the following native features:

Attributes: require, pattern, maxlength, min, max, placeholder

Input types: url, date, time, email, number

Elements: Use the element datalist to create input suggestions

E-mail:

User name: (only a-z characters)

Favorite color

...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'html5' }); </script>

Positioning the error messages

Each error message will be placed in the parent element of the input that it's referring to, by default. You can use the option errorMessagePosition to put the error messages in a certain element or in the top of the form.

<script>
// The element where the error messages should be placed
var $messages = $('#error-message-wrapper');

$.validate({
    validateOnBlur : false, // disable validation when input looses focus
    errorMessagePosition : $messages,
    scrollToTopOnError : false // Set this property to true if you have a long form
});
</script>

If you would like the error messages to be displayed together in the top of the form you set the property errorMessagePosition to top and disable the feature validateOnBlur.

E-mail:

Password:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> $.validate({ validateOnBlur : false, // disable validation when input looses focus errorMessagePosition : 'top' // Instead of 'element' which is default scrollToTopOnError : false // Set this property to true if you have a long form }); </script>

You can also point out the location of an error message for a certain input by using the attribute data-validation-error-msg-container.

E-mail:

Localization

In this section we will go through the different options when it comes to localization.


Using built-in languages

This plugin comes with all error dialogs translated into English, French, German, Spanish and Swedish. Use the configuration parameter lang when setting up the validation if you want to override the default language (which is English). Set the value of the lang-property to the corresponding language code of the desired translation.

$.validate({
    lang : 'de' // (supported languages are fr, de, se, sv, en)
});

Inline dialog declaration

You can use the attribute data-validation-error-msg if you want to declare an error message for a specific input.

User name:

...

If you have declared several validation rules on a single input you might want to have separate error dialogs for each rule. This is accomplished by using attribute data-validation-error-msg-[VALIDATION_RULE]

<input name="user"
    data-validation="required alphanumeric"
    data-validation-error-msg-required="You must enter a user name"
    data-validation-error-msg-alphanumeric="User name may only contain alphanumeric characters"/>

Custom language object

All error dialogs can be overwritten by passing an object to the setup function.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>

    var myLanguage = {
                errorTitle: 'Form submission failed!',
                requiredFields: 'You have not answered all required fields',
                badTime: 'You have not given a correct time',
                badEmail: 'You have not given a correct e-mail address',
                badTelephone: 'You have not given a correct phone number',
                badSecurityAnswer: 'You have not given a correct answer to the security question',
                badDate: 'You have not given a correct date',
                lengthBadStart: 'The input value must be between ',
                lengthBadEnd: ' characters',
                lengthTooLongStart: 'The input value is longer than ',
                lengthTooShortStart: 'The input value is shorter than ',
                notConfirmed: 'Input values could not be confirmed',
                badDomain: 'Incorrect domain value',
                badUrl: 'The input value is not a correct URL',
                badCustomVal: 'The input value is incorrect',
                andSpaces: ' and spaces ',
                badInt: 'The input value was not a correct number',
                badSecurityNumber: 'Your social security number was incorrect',
                badUKVatAnswer: 'Incorrect UK VAT Number',
                badStrength: 'The password isn\'t strong enough',
                badNumberOfSelectedOptionsStart: 'You have to choose at least ',
                badNumberOfSelectedOptionsEnd: ' answers',
                badAlphaNumeric: 'The input value can only contain alphanumeric characters ',
                badAlphaNumericExtra: ' and ',
                wrongFileSize: 'The file you are trying to upload is too large (max %s)',
                wrongFileType: 'Only files of type %s is allowed',
                groupCheckedRangeStart: 'Please choose between ',
                groupCheckedTooFewStart: 'Please choose at least ',
                groupCheckedTooManyStart: 'Please choose a maximum of ',
                groupCheckedEnd: ' item(s)',
                badCreditCard: 'The credit card number is not correct',
                badCVV: 'The CVV number was not correct',
                wrongFileDim : 'Incorrect image dimensions,',
                imageTooTall : 'the image can not be taller than',
                imageTooWide : 'the image can not be wider than',
                imageTooSmall : 'the image was too small',
                min : 'min',
                max : 'max',
                imageRatioNotAccepted : 'Image ratio is not accepted'
        };

    $.validate({
        language : myLanguage
    });
</script>

Other developers has also read

- How to change location of the error dialogs.

Advanced examples


Validate without submit

You can use the method $.fn.isValid(lang, config, displayErrors) if you want to validate a form programmatically. The function takes three arguments. The first argument being an object used to override the default error dialogs and the second argument being the configuration object. Use the third argument to tell the validation function if error dialogs should be displayed or not.

Here you can see an example code where we collect all the error dialogs during the validation and pass them on to a custom function displaying the error dialogs.

// Array used as error collection
var errors = [],

// Validation configuration
conf = {
    onElementValidate : function(valid, $el, $form, errorMess) {
       if( !valid ) {
          // gather up the failed validations
          errors.push({el: $el, error: errorMess});
       }
    }
},

// Optional language object
lang = {
    ...
};

// Manually load the modules used in this form
$.formUtils.loadModules('security, date');

$('#check-form').on('click', function() {
   // reset error array
   errors = [];
   if( !$(this).isValid(lang, conf, false) ) {
        displayErrors( errors );
   } else {
     // The form is valid
   }
});
</script>

Setup validation using only JavaScript

The whole point of this plugin is to not having to write JavaScript code when configuring form validations. If you feel the need to configure your form validation using JavaScript you probably should look into jquery-validation or formvalidation.io or any of the other superb form validation solutions out there.

But there is of course a way to accomplish this using jQuery-Form-Validator as well, by using the module jsconf.

<script>
    var config = {
      // ordinary validation config
      form : 'form'
      // reference to elements and the validation rules that should be applied
      validate : {
          'input-name' : {
                 validation : 'length, alphanumeric',
                 length : '5-12'
          },
          '.password-input-class' : {
                validation : 'length, strength'
                strength : '3',
                length : 'min10'
         },
         '#date-input-id' : {
                validation : 'date',
                format : 'dd/mm/yyyy'
         }
      }
    };

$.validate({
   modules : 'jsconf, security',
   onModulesLoaded : function() {
        $.setupValidation( config );
   }
});
</script>

The first call to $.validate should only contain the module declaration (it must also contain jsconf) and a callback for the event onModulesLoaded. In the callback you invoke the function $.setupValidation with the configuration object as argument.

The configuration object supports all the ordinary configuration options. Use the property validate to tell the jsconf-module which elements that should have validation rules.

All the configuration options for each validation rule is also supported. When applying them via markup they're all prefixed with data-validation. When declaring them using the jsconf-module you simply exclude the prefix.

    <input type="file" multiple="multiple" name="images"
           data-validation="length mime size"
           data-validation-optional="true"
           data-validation-length="min2"
           data-validation-allowing="jpg, png, gif"
           data-validation-max-size="512kb"
           data-validation-error-msg="Error message..."
            />

Would be translated into:

var conf = {
   ...
   validate : {
      images : {
             'validation' : 'length mime size',
             'optional' : true,
             'length' : 'min2'
             'allowing' : 'jpg, png, gif',
             'max-size' : '512kb',
             'error-msg' : 'Error message...'
      }
   }
};

Toggle disabled form submit

You can use the module toggleDisabled if you want to have the submit button disabled until the form is completely filled out.

$.validate({
    modules : 'toggleDisabled',
    disabledFormFilter : 'form.toggle-disabled',
    showErrorDialogs : false
});

Use the property disabledFormFilter to target specific forms on your page. By omitting the property the disabled feature will become enabled on all forms. Use the property showErrorDialogs to tell the module whether or not to display error dialogs (defaults to true).

Writing a custom validator

You can use the function $.formUtils.addValidator() to add your own validation function. Here's an example of a validator that checks if the input contains an even number.

...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script> <script> // Add custom validation rule $.formUtils.addValidator({ name : 'even_number', validatorFunction : function(value, $el, config, language, $form) { return parseInt(value, 10) % 2 === 0; }, errorMessage : 'You have to answer with an even number', errorMessageKey: 'badEvenNumber' }); // Setup form validation $.validate(); </script>
Note: you can also write inline regexp if wanting to do a custom validation

Required properties passed into $.formUtils.addValidator

name - The name of the validator, which is used in the validation attribute of the input element.

validatorFunction - Callback function that validates the input. Should return a boolean telling if the value is considered valid or not.

errorMessageKey - Name of language property that is used in case the value of the input is invalid.

errorMessage - An alternative error message that is used if errorMessageKey is left with an empty value or isn't defined in the language object. Note that you also can use inline error messages in your form.

The validation function takes these five arguments:

  • value — the value of the input thats being validated
  • $el — jQuery object referring to the input element being validated
  • config — Object containing the configuration of this form validation
  • language — Object with error dialogs
  • $form — jQuery object referring to the form element being validated

Creating a custom module

A "module" is basically a javascript file containing one or more calls to $.formUtils.addValidator(). The module file should either have the file extension .js (as an ordinary javascript file) or .dev.js

Using the file extension .dev.js will tell $.formUtils.loadModules to always append a timestamp to the end of the URL, so that the browser never caches the file. You should of course never use .dev.js on a production website.

Loading your module

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<script>
    // Load my custom module
    $.formUtils.loadModules('mymodule.dev', 'js/validation-modules/');

    // Setup validation on all forms
    $.validate();
</script>

The first argument of $.formUtils.loadModules is a comma separated string with names of module files, without file extension (add .dev if the file name is for example mymodule.dev.js, this will ensure you that the browser never caches the javascript).

The second argument is the path where the module files are located. This argument is optional, if not given the module files has to be located in the same directory as the core modules shipped together with this jquery plugin.

License

This plugin is dual licensed under the MIT or GPL Version 2 licenses.

Search