jQuery Validate Remote Validation

Simple demo

by bizamajig

HTML

<script src="https://raw.github.com/jzaefferer/jquery-validation/master/jquery.validate.js"></script>
<h3>Remote validation example</h3>
<p>Click on `validate` button and inspect the networks tab to see the remote AJAX call being made to validate the email address. If the remote server returns a response which is not `true` or `"true"`, the validation fails.</p>

<form id="fail">
    <legend>Failing form</legend>
    <input type="email" name="email" value="[email protected]" />
    <button type="submit">Validate</button>
</form>

<p>Below is an example of a remote validation which returns `true`</p>

<form id="good">
    <legend>Valid form</legend>
    <input type="email" name="email" value="[email protected]" />
    <button type="submit">Validate</button>
</form>

<h3>Notes</h3>

<ul>
    <li>Different instances of validators tend to cancel each other's AJAX requests</li>
</ul>

CSS

form input.valid { border: solid 1px green; }
form input.error { border: solid 1px red; }

JavaScript

$(function () {
    
    var $fail = $('form#fail');
    var $good = $('form#good');
    var common = {
        debug: true,
        onfocusout: true,
        onsubmit: true,
        submitHandler: function (form) {
            alert('Form is error free and can be submitted!');
            // $form.submit() should be called from here
        },
        invalidHandler: function (event, validator) {
            alert('Form contains errors and cannot be submitted.');
            // you don't need this handler, it's just here for demo
        }
    };
    
    // Failing form asks mock AJAX to return an error message
    $fail.validate($.extend({}, common, {
        rules: {
            email: {
                required: true,
                email: true,
                remote: {
                    url: '/echo/json/',
                    type: 'POST',
                    data: {
                        json: JSON.stringify("duplicate email"),
                        delay: 3
                    }
                }
            }
        }
    }));
    
    // Valid form returns true
    $good.validate($.extend({}, common, {
        rules: {
            email: {
                required: true,
                email: true,
                remote: {
                    url: '/echo/json/',
                    type: 'POST',
                    data: {
                        json: JSON.stringify(true),
                        delay: 3
                    }
                }
            }
        }
    }));
    
});