Skip to content

Instantly share code, notes, and snippets.

@samuelcole
Created January 4, 2011 21:03
Show Gist options
  • Select an option

  • Save samuelcole/765407 to your computer and use it in GitHub Desktop.

Select an option

Save samuelcole/765407 to your computer and use it in GitHub Desktop.
Determines validity by running through an array of functions in the data object.
// Checks if a DOM object is valid.
// Expects an array of functions in data('validations') that return true when
// valid.
//
// Triggers field_invalid or field_valid.
// Calls options.invalid() or options.valid().
$.fn.validate = function(options) {
var $this = $(this);
/* $this.data('validations') is an array of functions, each of which
* accepts the value of the form field, and returns true if it passes the
* validation, and false if it fails.
*/
if($this.data('validations')) {
var invalid = false;
$.each($this.data('validations'), function() {
if(!this($this.val())) {
invalid = true;
return false;
}
});
if(invalid) {
$this.trigger('field_invalid');
$this.focus().select();
if(options && options.invalid) options.invalid();
} else {
$this.trigger('field_valid');
if(options && options.valid) options.valid();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment