views:

1383

answers:

3

I have simple issue -- I would like to check a field to see if its 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 recieve is "val() is not an object".

UPDATE: Turned out that the real issue was that I had my element name set and not the Id.

Thanks, George

+2  A: 

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;
}
karim79
I get val() is not an object with this as well.
George
@George Johnston - because I had just typed it straight into the browser against my better judgement, and it was completely borked. Try now, if you will.
karim79
+2  A: 

One of the best answers to this ever is to simply try to convert the value to a number and see what happens. The following solution completely avoids Regex altogether, and is surprisingly elegant. Check this post:

http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric

David Morton
I used this solution, but Karim really answered the question I asked. Thanks though!
George
A: 

use

if($("#afield").val){ // do something here };

so loose the ' != "" ' its not needed.

derk