Alfred
Alfred

Reputation: 21396

Jquery validate plugin number validation with special characters

I am using jquery validate plugin to validate a Number field in my form.

The script for validation is

NUMBER: {
    required: true,
        number: true,
    minlength: 4,
    },

which validates my formfield <input name="NUMBER" type="text" id="NUMBER" value="" maxlength="4" >

but, i want to include (or allow) special characters "+", "-", and ",", and word "NA" in my formfield. How can I make this possible?? The word "NA" should be validated when it is alone, without any other letter or number..

Thanks in advance.. :)

blasteralfred

Upvotes: 3

Views: 16616

Answers (2)

user1553777
user1553777

Reputation: 241

Check this one http://archive.plugins.jquery.com/project/jvalidation more flexible and easy to use with less than 3 k size.

in your case you can use default data-validate-format validator

<input data-validate-format='/^([0-9,\+-]{0,4}|NA)$/' />

Check regex I put as value of the attribute

They have a sample for extending with optional validations such as numbers

$.fn.validations.options.validators.age = function(){
  return this.val()>0&&this.val()<100;
}

and in your html you add sth like

<input data-validate-age='true' data-validate-error='.err1' />
<div class='err1'>Age should be more than 0 and less than 100!</div>

Check Full Documentation for jQuery Validation Plugin

Upvotes: 1

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You can accomplish this with your own custom rule for validator:

$.validator.addMethod("custom_number", function(value, element) {
    return this.optional(element) || value === "NA" ||
        value.match(/^[0-9,\+-]+$/);
}, "Please enter a valid number, or 'NA'");

This validates the field if it's optional, equal to "NA" or meets the regular expression.

And then you would just apply this new rule to whatever field you want:

$("form").validate({
    rules: {
        number: {
            required: true,
            custom_number: true,
            minlength: 4
        }
    }
});

Obviously, you should replace the name custom_number with something a bit more descriptive.

Check out a working example here: http://jsfiddle.net/andrewwhitaker/RtK2p/1/

Upvotes: 7

Related Questions