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:
- http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery
- http://stackoverflow.com/questions/5180259/jquery-validation-regex-for-digits-with-hyphens
- http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UFcuc1GQmTU
- http://stackoverflow.com/questions/9882693/jquery-match-regex
No comments:
Post a Comment