Form validation made easy

jQuery Form Validator is a feature rich 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 jQuery 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 as well as bower and github.

Basic example

Name (4 characters minimum):

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.1.47/jquery.form-validator.min.js"></script> <script> $.validate(); </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)












                

Numbers





















                

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

Average points

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

E-mail


                

URL:s


                

Date






                

See the date module for further validators.

Alphanumeric






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


<script>
$("[name='newsletters[]']:eq(0)")
    .valAttr('','validate_checkbox_group')
    .valAttr('qty','1-2')
    .valAttr('error-msg','chose 1, max 2');
</script>

Regexp



                

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>

Example form

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.1.47/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.

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.

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.1.47/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> ...

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.1.47/jquery.form-validator.min.js"></script>
<script>
    $.validate({
        modules : 'security'
    });
</script>

Password confirmation

Password (at least 8 characters) Confirm password

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.1.47/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 server side 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']) ) {
    $userFactory = new UserFactory( DataStorage::instance() );
    $user = $userFactory->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);

Simple spam check

<?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>
...

Example form

<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)

What is the sum of 3 + 4?

<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.1.47/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'security', onModulesLoaded : function() { $('input[name="pass_confirmation"]').displayPasswordStrength(); } }); </script> ...

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.1.47/jquery.form-validator.min.js"></script> <script> // Add validation $.formUtils.addValidator({ name : 'even_number', validatorFunction : function(value, $el, config, language, $form) { return parseInt(value, 10) % 2 === 0; }, errorMessage : 'You have to give 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.1.47/jquery.form-validator.min.js"></script>
<script>
    $.formUtils.loadModules('mymodule.dev', 'js/validation-modules/');
</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 is 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.

Setup and configuration

The code below shows you all the different configuration options you can use
when setting up the validation.


Setup

// Setup form validation on all forms on page
$.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 is loaded!');
    }
});

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

Validation callbacks

There are three 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 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.
  • 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() {
            alert('Validation failed');
        },
        onSuccess : function() {
            alert('The form 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'
            }
        }
    });

    // Validation event listeners
    $('input')
        .bind('beforeValidation', function() {
            console.log('Input "'+this.name+'" is about to become validated');
        })
        .bind('validation', function(evt, isValid) {
            console.log('Input "'+this.name+'" is ' + (isValid ? '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. 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>
    ...

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
});

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.1.47/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>

Localization

All error dialogs can be overwritten by passing an object to the setup function. You can also use the attribute data-validation-error-msg if you want to declare an error message for a specific input.

User name:

...
<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.1.47/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 : 'You must give an answer between ', lengthBadEnd : ' characters', lengthTooLongStart : 'You have given an answer longer than ', lengthTooShortStart : 'You have given an answer shorter than ', notConfirmed : 'Values could not be confirmed', badDomain : 'Incorrect domain value', badUrl : 'The answer you gave was not a correct URL', badCustomVal : 'You gave an incorrect answer', badInt : 'The answer you gave 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 answer you gave must contain only alphanumeric characters ', badAlphaNumericExtra: ' and ', wrongFileSize : 'The file you are trying to upload is too large', wrongFileType : 'The file you are trying to upload is of wrong type', groupCheckedRangeStart : 'Please choose between ', groupCheckedTooFewStart : 'Please choose at least ', groupCheckedTooManyStart : 'Please choose a maximum of ', groupCheckedEnd : ' item(s)' }; $.validate({ language : myLanguage }); </script>

File validators

This module contains validators needed when validating file uploads.

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.1.47/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 against the extension ".pdf")






Validating multiple files:

<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="You have to upload at least two images (max 512kb each)"
    />

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.1.47/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.1.47/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

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.1.47/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'location', onModulesLoaded : function() { $('input[name="state"]').suggestCountry(); $('input[name="country"]').suggestState(); } }); </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.1.47/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

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.1.47/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'date' }); </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.1.47/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.1.47/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 county (län)

                    
                

Validate municipality (kommun)

                    
                

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.1.47/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'sweden', onModulesLoaded : function() { $('input[name="county"]').suggestSwedishCounty(); $('input[name="municipality"]').suggestSwedishMunicipality(); } }); </script>

Example form

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.1.47/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'sweden', onModulesLoaded : function() { $('input[name="lan"]').suggestSwedishCounty(); $('input[name="kommun"]').suggestSwedishMunicipality(); } }); </script> ...

License

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

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.1.47/jquery.form-validator.min.js"></script>
<script>
    $.validate({
        modules : 'uk'
    });
</script>

VAT

                    
                

Credits

Want to contribute? All you have to do is to fork this project on github and do a pull request.


Author

Victor Jonsson

Contributors

Joel Sutherland
Steve Wasiura
Matt Clements
Josh Toft
@dfcplc
Andree Wendel
Nicholas Huot
@repkit
Alexandar Blagotic
Yasith Fernando
@S0L4R1S
Erick Lisangan

Additional credits

Scott Gonzales (URL regexp)
Darren Mason (Password strength meter)