Monday, September 17, 2012

functions and regex in jQuery

One way to validate that a form field holds a number with jQuery is like this:

var detail21 = $(rows[21]).find('input:text:first');
var matches = (detail21).find('input:first').val()).match(/^[0-9]+([0-9]+)*$/);
if(!matches) {

 
 

But here is something more interesting!

var detail21 = $(rows[21]).find('input:text:first');
$(detail21).ForceNumericOnly();

 
 

This function will only allow you to type numbers into the form field in question!

jQuery.fn.ForceNumericOnly = function()
{
   return this.each(function()
   {
      $(this).keydown(function(e)
      {
         var key = e.charCode || e.keyCode || 0;
         return (
            key == 8 ||
            key == 9 ||
            key == 46 ||
            (key >= 37 && key <= 40) ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105));
      });
   });
};

 
 

I figured this out with:

No comments:

Post a Comment