5

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

2
  • The problem is that the empty string is not a valid number. I don't know enough about that plugin to know how to get the (perfectly reasonable) behavior you want.
    – Pointy
    Oct 28, 2011 at 12:22
  • Check [this demo][1] [1]: docs.jquery.com/Plugins/Validation/Methods/number Change required to false and should be ok, plus you can show your html for more information.
    – Mindaugas
    Oct 28, 2011 at 12:27

5 Answers 5

6

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
3

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.

0

Works fine @ http://jsfiddle.net/b3RmV/1/

Shows the error only on the non numeric chars, else the form should be submitted.

0

It works fine cause there is an additional stuff in internal method which must be add into custom method :

// http://docs.jquery.com/Plugins/Validation/Methods/number
number: function(value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
},

Notice this.optional(element) ||

you need to add this on your custom method to get custom work properly when no required

by the way thanks for this post, which saw me the way to find this.

-1

You have to use <input> with type attribute equals to text, not number:

<input type="text" id="phone" name="phone" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.