jQuery: enhancing form validation with Deferred Objects

We can use jQuery's Deferred Objects to enhance form validation.

Deferred Objects can be used as follows:


"use strict";

var validate = function( value ) {
  var def = $.Deferred();
  var reg = /^\d+$/;
  if( reg.test( value ) ) {
    def.resolve();
  } else {
    def.reject();
  }
  return def.promise();
};

We're testing the actual validity of a string that must contain only digits. Then our validation routine will take advantage of the chaining features of Deferred Objects:


"use strict";

$( "[name=id]" ).on( "keydown", function() {
  var $input = $( this );
  var val = $input.val();
  
  $.when( validate( val ) ).then(function() {
     $input.removeClass( "error" );
     $input.next().css( "opacity", 1 );
  }).fail(function() {
     $input.addClass( "error" );
     $input.next().css( "opacity", 0 );
  });
});

You can see the complete example here.

Back to top