Alex Rivera | Logout

Validate that text field is numeric usiung jQuery

Asked 2010-03-09T00:39:52.443
23

I have a simple issue -- I would like to check a field to see if it's an integer if it is not blank. I'm not using any additional plugins, just jQuery. My code is as follows:

if($('#Field').val() != "")
{
    if($('#Field').val().match('^(0|[1-9][0-9]*)$'))
    {
        errors+= "Field must be numeric.<br/>";
        success = false;
    }
}

...It doesn't seem to work. Where am I going wrong?

The error I receive is val() is not an object.


It turned out that the real issue was that I had my element name set and not the Id.

Edit
Report

1 Answer

23

This should work. I would trim the whitespace from the input field first of all:

if($('#Field').val() != "") {
    var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(!intRegex.test(value)) {
        errors += "Field must be numeric.<br/>";
        success = false;
    }
} else {
    errors += "Field is blank.</br />";
    success = false;
}
answered 2010-03-09T00:54:31.900

Your Answer