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!

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer and well done going out of your way to do an example
1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.