Skip to content

Instantly share code, notes, and snippets.

@shwoodard
Created March 8, 2009 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shwoodard/75577 to your computer and use it in GitHub Desktop.
Save shwoodard/75577 to your computer and use it in GitHub Desktop.
$.fn.validatesNumericality = function(options) {
return this.each(function() {
var el = $(this);
// TODO: I18n
var thousandsSep = ',';
var decimalSep = '.';
var settings = $.extend({
invalidClass: 'invalid-numericality',
onlyInteger: false,
validatesOn: ['change', 'blur'],
when: function() {return true;}
}, options);
el.bind(settings.validatesOn.join(' '), function() {
if (settings.when(el)) {
var val = el.val().replace(new RegExp("/"+thousandsSep+"/", 'g'), '');
if (decimalSep !== '.') {
val = val.replace(RegExp("/"+decimalSep+"/"), '.');
}
if (isNaN(val)) {
el.trigger('invalid')
.trigger('invalid-numericality')
.closest('fieldset')
.addClass(settings.invalidClass);
} else {
el.trigger('valid')
.trigger('valid-numericality')
.closest('fieldset')
.removeClass(settings.invalidClass);
}
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment