Skip to content
4Stern edited this page Mar 23, 2017 · 13 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['remoteUserNameValidationRule'] = {
        async: true,
        validator: function ( val, parms, callback ) { 
            var defaults = {
                url: '/my/rest/validation/uri',
                type: 'POST',
                success: function(data) {
                  callback(/* true or false depending on what you get back in data */);
                }
            };

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

After creation of the validation rule(s) you need to register them:

ko.validation.registerExtenders();

Lastly, what do I do while validation is happening async?

All validated observable objects now have an isValidating property that is observable (so you can subscribe to it)

var username = ko.observable().extend({ remoteUserNameValidationRule: { url: '/Users/ValidateUserName', data: username }});

// setting it will trigger validation
username.isValidating.subscribe(function(isValidating){
     if(!isValidating && username.isValid()){
         // save the username or whatever you do
     }
});

Anonymous async rules

Async validation rules can also be created anonymously. Here's an example of an anonymous async rule using jQuery AJAX:

var username = ko.observable().extend({
		validation: {
			async: true,
			validator: function (val, params, callback) {

				var options = {
					url: 'your/validation/url',
					type: 'POST',
					data: val,
					success: callback
				};

				$.ajax(options);
			},
			message: 'Your validation message'
		}
	});