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.
精彩评论