1

I'm using the jQuery Validate plugin and want to validate an input field using a fixed amount of numbers with a dash in the middle like so: XXXXXX-XXXX. I know how to validate numbers but how can I get the plugin to validate this specific format?!

Thanks!

Ismailp
  • 2,333
  • 4
  • 37
  • 66

2 Answers2

6

You could use a regex. Add a custom validator method as illustrated here:

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var re = new RegExp(regexp);
        return re.test(value);
    },
    "Please check your input."
);

And then attach it to the input element that you need to validate:

$('#id_of_textbox').rules('add', { regex: '^[0-9]{6}-[0-9]{4}$' })

or if you are using it with the form:

$('#id_of_form').validate({
    rules: {
        name_of_textbox: {
            regex: '^[0-9]{6}-[0-9]{4}$'
        }
    },
    messages: {
        name_of_textbox: {
            regex: 'Please provide a valid input for this field'
        }
    }
});

And here's a live demo.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You can do Regest with Javascript as basic as that.. same way you can include the regest with jquery plugin as well.

Jigar Pandya
  • 6,004
  • 2
  • 27
  • 45