views:

32

answers:

1

I'm having a problem validating entries on a form using jQuery and the Validation plugin. The entries must be either zero or a positive number. I've had no trouble with a method to detect negative numbers (or NaNs), but I've had any method work to detect empty entries or ones with nothing but spaces.

The relevant code:

//WORKS
//require positive numbers/floats
$.validator.addMethod('requirePositiveNumber', function (value){
if ((isNaN(value)) || (value < 0) ){
    return false;
}else{
   return true;
}
     }, "Please enter a positive amount"
);

//DOES NOT WORK
//require no spaces
$.validator.addMethod("noSpace",function(value,element)
{
    return this.optional(element) || /^[.\d]+/i.test(value);
},"no spaces please");

//DOESNT WORK EITHER
$.validator.addMethod("noSpace", function(value, element){
        if (value.indexOf(" ") < 0 && value !=""){
            return true;
        }else{
            return false;
        }
    }, "please enter a positive amount"
    );

Neither does testing just for whitespace.

A: 

Assuming "myform" is your form's ID and "myfield" is your field's name, this should do the trick:

"isPositiveNumber" jQuery validator rule:

$.validator.addMethod("isPositiveNumber", function(value, element) {
    return this.optional(element) || /^[0-9.]+$/i.test(value);
}, "Please enter a positive amount");

Validation script:

$("#myform").validate({
    rules: {
        myfield: { required: true, isPositiveNumber: true }
    },
    messages: {
        // Overwrite the default required message
        myfield: { required: 'Please enter a positive amount' }
    }
});

Using the built-in required: true rule on the field, will stop the field from validating if it's either empty or just a bunch of spaces.

FreekOne
Thanks, but unfortunately this didn't do it. It works for everything but a null or a series of spaces; everything else will trigger the validation as soon as the user leaves the input box. I've repeated this under Firefox 3.6 and IE8. I know I'm doing something wrong on the test...but can't figure out what.
Please see my updated response. Note the use of the built-in `required: true` method. That is what is going to prevent an empty field or just a bunch of spaces from validating, nicely disguised with the same error message that your custom method outputs. I have tested this locally and it works just fine.
FreekOne