This site contains the document for old version. Please upgrade to the latest version v1.0.0

remote validator

Perform remote checking via Ajax request

Validators

Options

* — Required option

Option HTML attribute Type Description
crossDomain data-fv-remote-crossdomain Boolean It's same as the crossDomain option of jQuery's ajax.
data data-fv-remote-data Object|Function

The data sent to remote URL.

You don't need to use this option if there is only field, defined as field name, sent to the remote URL.

If you want to use dynamic data, then use a callback as following:

data: function(validator, $field, value) {
    // validator is FormValidation instance
    // $field is the field element
    // value is the field value

    // Return an object
    return {
        key: value,
        otherKey: otherValue
    };
}

When using data-fv-remote-data attribute, its value must be an encoded JSON string.

dataType data-fv-remote-datatype String

The type of data which is returned by remote server. It's same as the dataType option of jQuery's ajax.

The available values are json default, jsonp

delay data-fv-remote-delay Number The Ajax request created by the remote validator is only fired once in the delay duration time.
message data-fv-remote-message String The error message. The dynamic message is supported
name data-fv-remote-name String The name of field which need to validate
type data-fv-remote-type String

The method used to send data to back-end. It can be GET default or POST

From v0.5.2, the type option is GET, by default.
url* data-fv-remote-url String|Function The remote URL.
If you want to use a dynamic URL, then use a callback as following:
url: function(validator, $field, value) {
    // validator is FormValidation instance
    // $field is the field element
    // value is the field value

    return 'the URL';
}
validKey data-fv-remote-validkey String

The valid key. It's valid by default.

This option is useful when connecting to external remote server or APIs provided by 3rd parties.

When setting options via HTML attributes, remember to enable the validator by setting data-fv-remote="true".
The message and other options can be updated on the fly via the updateMessage() and updateOption() methods

The crossDomain, dataType, validKey options are mostly used when you need to connect to external API endpoint. This example shows how to connect and use the Mailgun API to validate an email address.

The remote URL has to return an encoded JSON of array containing the valid key (the key name can be changed by the validKey option):

{ "valid": true }

or

{ "valid": false }
The validator is ignored if the remote URL responses { "valid": null }
Look at this example if you want to attach more data to the returned value and reuse them later

Improving the performance

By default, the plugin will send an Ajax request to your back-end whenever you enter a character in field. If the back-end takes time to process the request, it might slow down the website. In order to improve the performance, you can use following tips:

It's also recommended to use the tips introduced in the Getting notified while field is being validated example to improve the user experience of the application

Using delay option

By setting the delay option, the Ajax request is only fired once in the specific duration time.

$('#registrationForm').formValidation({
    framework: 'bootstrap',
    fields: {
        username: {
            validators: {
                remote: {
                    url: '/path/to/backend/',
                    type: 'POST',
                    delay: 2000     // Send Ajax request every 2 seconds
                }
            }
        }
    }
});

Using threshold option

The threshold option indicates value that asks validators not to perform validations unless the length of field value is greater than this number.

In the snippet code below, the remote validator will not send Ajax request until the username field has at least 5 characters:

$('#registrationForm').formValidation({
    framework: 'bootstrap',
    fields: {
        username: {
            threshold: 5,
            validators: {
                remote: {
                    url: '/path/to/backend/',
                    type: 'POST'
                }
            }
        }
    }
});

Using verbose option

Client first, server last. If the field uses multiple validators, the validators processed in the client should be done first. The remote validator is only processed once the field passes all other validators.

Using the verbose option is solution for this approach. Setting verbose: false will stop validations when there is one failure validator.

In the following code, the remote validator is only processed if the field satisfies all notEmpty, stringLength, regexp validators.

$('#registrationForm').formValidation({
    framework: 'bootstrap',
    fields: {
        username: {
            verbose: false,
            validators: {
                notEmpty: {
                    message: 'The username is required'
                },
                stringLength: {
                    min: 6,
                    max: 30,
                    message: 'The username must be more than 6 and less than 30 characters long'
                },
                regexp: {
                    regexp: /^[a-zA-Z0-9_\.]+$/,
                    message: 'The username can only consist of alphabetical, number, dot and underscore'
                },
                // Place the remote validator in the last
                remote: {
                    url: '/path/to/backend/',
                    type: 'POST'
                }
            }
        }
    }
});

Examples

Basic example

The following example shows how to use a remote back-end to check if a given username is already taken or not.

<form id="registrationForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Username</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="username" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#registrationForm').formValidation({
        framework: 'bootstrap',
        fields: {
            username: {
                message: 'The username is not valid',
                validators: {
                    // The validator will create an Ajax request
                    // sending { username: 'its value' } to the back-end
                    remote: {
                        message: 'The username is not available',
                        url: '/path/to/backend/',
                        type: 'POST'
                    }
                }
            }
        }
    });
});
</script>
<?php
// The back-end then will determine if the username is available or not,
// and finally returns a JSON { "valid": true } or { "valid": false }
// The code bellow demonstrates a simple back-end written in PHP

// Get the username from request
$username = $_POST['username'];

// Check its existence (for example, execute a query from the database) ...
$isAvailable = true; // or false

// Finally, return a JSON
echo json_encode(array(
    'valid' => $isAvailable,
));

Sending static data example

For example, there is same back-end for validating both username and email address. The back-end uses additional parameter named type to determine which field is going to be validated.

<form id="registrationForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Username</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="username" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-lg-3 control-label">Email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="email" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#registrationForm').formValidation({
        framework: 'bootstrap',
        fields: {
            username: {
                message: 'The username is not valid',
                validators: {
                    // Send { username: 'its value', type: 'username' } to the back-end
                    remote: {
                        message: 'The username is not available',
                        url: '/path/to/backend/',
                        data: {
                            type: 'username'
                        },
                        type: 'POST'
                    }
                }
            },
            email: {
                message: 'The email address is not valid',
                validators: {
                    // Send { email: 'its value', type: 'email' } to the back-end
                    remote: {
                        message: 'The email is not available',
                        url: '/path/to/backend/',
                        data: {
                            type: 'email'
                        },
                        type: 'POST'
                    }
                }
            }
        }
    });
});
</script>
<?php
// The code bellow demonstrates a simple back-end written in PHP
// Determine which field you want to check its existence
$isAvailable = true;

switch ($_POST['type']) {
    case 'email':
        $email = $_POST['email'];
        // Check the email existence ...
        $isAvailable = true; // or false
        break;

    case 'username':
    default:
        $username = $_POST['username'];
        // Check the username existence ...
        $isAvailable = true; // or false
        break;
}

// Finally, return a JSON
echo json_encode(array(
    'valid' => $isAvailable,
));

Sending dynamic data example

For instance, the registration form need to validate both the username and emails.

<form id="registrationForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Username</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="username" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-lg-3 control-label">Email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="email" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-lg-3 control-label">Password</label>
        <div class="col-lg-5">
            <input type="password" class="form-control" name="password" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#registrationForm').formValidation({
        framework: 'bootstrap',
        fields: {
            username: {
                message: 'The username is not valid',
                validators: {
                    remote: {
                        url: '/path/to/backend/',
                        // Send { username: 'its value', email: 'its value' } to the back-end
                        data: function(validator, $field, value) {
                            return {
                                email: validator.getFieldElements('email').val()
                            };
                        },
                        message: 'The username is not available',
                        type: 'POST'
                    }
                }
            },
            email: {
                validators: {
                    remote: {
                        url: '/path/to/backend/',
                        // Send { email: 'its value', username: 'its value' } to the back-end
                        data: function(validator, $field, value) {
                            return {
                                username: validator.getFieldElements('username').val()
                            };
                        },
                        message: 'The email is not available',
                        type: 'POST'
                    }
                }
            }
        }
    });
});
</script>

Overriding name example

By default, it will be set as the name of field. You can override the name option by using the data-fv-remote-name attribute.Here are two cases which you might need to use this attribute.

Using different names for same field

For example, the Sign up and Profile forms use the same back-end URL to validate the email address which is declared with different name.

In this case, use the same data-fv-remote-name attribute and the back-end will get the same data key.

<!-- In the signup form, the email address field is named as "login" -->
<form id="signupForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="login" data-fv-remote-name="email" />
        </div>
    </div>
</form>
<!-- In the edit profile form, the email address field is named as "email" -->
<form id="profileForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control" name="email" data-fv-remote-name="email" />
        </div>
    </div>
</form>

Using same backend for different fields

Assume that the profile form asks you to update multiple email address (primary, secondary, for example). These emails will be validated by the same backend.

In this case, just use the same data-fv-remote-name attribute for these email address fields.

<form id="profileForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-lg-3 control-label">Primary email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control"
                name="primary_email" data-fv-remote-name="email" />
        </div>

        <label class="col-lg-3 control-label">Secondary email</label>
        <div class="col-lg-5">
            <input type="text" class="form-control"
                name="secondary_email" data-fv-remote-name="email" />
        </div>
    </div>
</form>

More examples

Related validators

The following validators might be useful to you: