0

I'm using the jQuery Validate plugin for a registration form and have run into a predicament...

I need the username field to be not only required, but also follow a specific pattern: The first 5 characters MUST be numbers, and the rest and be anything the user wants.

I found this other question which might be along the lines of what I need to do. Is there a way to accomplish this?

If there isn't a way to accomplish this, I think I have a workaround... Have two fields visible (one for 5 numbers & one for the other characters at the end). I could then have a hidden field that appends the two fields' values together and then that's what gets submitted as the username. That way, I can enforce numbers only and a length of 5 for the numbers field. It's dirty, but it may work.

Thanks in advance.

Community
  • 1
  • 1
scferg5
  • 2,003
  • 5
  • 22
  • 28

2 Answers2

1

How about using this regular expression:

/^[\d]{5}.*/

in conjunction with the answer you referred to?

For example:

jQuery.validator.addMethod("accepted_format", function(value, element, param) {
  return value.match(/^[\d]{5}.*/);
});

rules: {
  field: 'accepted_format'
}
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64
0

Using the linked questions answer, creating the accept method, using your requirement, and the required rule you end up with the below, let me know any issues.

jQuery.validator.addMethod("custom_accept", function(value, element, param) {
  return value.match(new RegExp( param ));
});

var rules = { 
  elementName: {
    custom_accept: "/^[\d]{5}.*/",
    required: true
  } 
}
lsl
  • 4,371
  • 3
  • 39
  • 54