开发者

Problems with jquery validation against spaces

开发者 https://www.devze.com 2023-01-13 14:32 出处:网络
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 negativenu

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开发者_如何学Python 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号