I am using the jQuery Validation plugin
I want one of my fields to be a number, but it is not a required field.
The thing is, when I set number: true
, it makes the field required. Why is that? I tried to add required: false
with number: true
, but to no avail.
This my code:
name : {
required:false,
number:true
}
I am not setting an error message, but it shows the default error message: "please enter a valid number."
In the source code they are using this regex to validate a number:
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/
When the field is empty( ""
), it does not pass the test:
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test("")
//false
You might try writing your own validator. It's not too hard. Something like:
$.validator.addMethod
(
"number2",
function (value, element)
{
// Remove numberish characters.
value = value.replace("$", "").replace(",", "");
// A regex might be better but this works too.
if (!isNaN(parseFloat(value)))
{
$(element).val(parseFloat(value));
return true;
}
else if (value === "") // handle empty value
{
return true;
}
else
{
return false;
}
},
"Numeric only."
);
Then apply the rule, for example:
$.validator.addClassRules("numeric", { number2: true });
A variation of this theme can be applied to integer or currency values and, of course, you could get quite complex with validation and "cleaning" of data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With