Skip to content
ericmbarnard edited this page Apr 13, 2012 · 6 revisions

####Async Rules are pretty handy for dealing with AJAX and other asynchronous validation operations####

Any validator in a validation rule can be async by setting the async flag on the rule:

ko.validation.rules['exampleAsync'] = {
        async: true, // the flag that says "Hey I'm Async!"
        validator: function (val, otherVal, callBack) { // yes, you get a 'callback'
           
            /* some logic here */

            // hand my result back to the callback
            callback( /* true or false */ );
            // or if you want to specify a specific message
            callback( /* { isValid: true, message: "Lorem Ipsum" } */ );
        },
        message: 'My default invalid message'
    };

Thus, here would be your classic jQuery AJAX validation rule:

ko.validation.rules['remote'] = {
        async: true,
        validator: function ( val, parms, callBack ) { 
            var defaults = {
                url: '/my/rest/validation/uri',
                type: 'POST',
                success: callback
            };

            var options = $.extend( defaults, parms );
            
            $.ajax( options );
        },
        message: 'Default Invalid Message'
    };
Clone this wiki locally