Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'number:true' makes field is required in jquery validation

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."

like image 535
Kanishka Panamaldeniya Avatar asked Oct 28 '11 12:10

Kanishka Panamaldeniya


2 Answers

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
like image 155
Esailija Avatar answered Nov 05 '22 12:11

Esailija


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.

like image 42
slopapa Avatar answered Nov 05 '22 12:11

slopapa