1

i have the following validation on a form field:

$(".controlscard input").blur(function() {
var re = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
if(re.test(document.getElementById("register_coachcard_no").value))
{
   $(this).css('border-color','green');
     $(this).siblings('.info').css('display','none');
     $(this).siblings('.error').css('display','none');
     $(this).siblings('.valid').css('display','inline-block');   
    $("#email_error40111").hide();

}
else
{
      $(this).css('border-color','red');
     $(this).siblings('.info').css('display','none');
     $(this).siblings('.valid').css('display','none');
     $(this).siblings('.error').css('display','inline-block');
   $('#registerErrors').show();
  $('#email_error40111').remove();
  $('#registerErrors').append('<p id="email_error40111">Coachcard must contain at least 1 letter and 1 number</p>');
}});

The above basically checks if the entered content contains 1 letter and 1 number.

I need to put something in place where, if the value length is 8 characters, it will need to check for upto 2 letters, and then 6 numbers.

If the value length is 9 characters, then only numbers can be entered.

Any suggestions on what i can do?

Cheers, Dan

5
  • /^[a-zA-Z]\d|[a-zA-Z]{2}\d{6}|\d{9}$/i - Is this what you want? Commented May 16, 2013 at 14:14
  • what does that cover? Commented May 16, 2013 at 14:15
  • Exactly as you said. | specifies a logical OR. (1 letter, one number OR two letters, 6 numbers OR 9 numbers). Commented May 16, 2013 at 14:16
  • yes, just tested! i need to be able to allow 1 or 2 letters with the length of 8, not just 1 Commented May 16, 2013 at 14:17
  • Sorry just tested again! all ok :) Commented May 16, 2013 at 14:17

1 Answer 1

1

I think you want a regex like this:

/^[a-zA-Z]\d|[a-zA-Z]{2}\d{6}|\d{9}$/i 

The | indicates a logical OR, so if one of these holds, it will match:

  • 1 letter followed by 1 number
  • 2 letters followed by 6 numbers
  • 9 numbers

You mentioned that you wanted to match 1 or 2 letters in the second case, but I wasn't sure how this fit with your requirement of 8 characters. You could modify it to accept 1 or 2 letters for 7 or 8 total characters like so:

/^[a-zA-Z]\d|[a-zA-Z]{1,2}\d{6}|\d{9}$/i 

Edit:

From comments, adjusted regex:

/^[a-zA-Z]\d|[a-zA-Z]{1}\d{7}|[a-zA-Z]{2}\d{6}|\d{9}$/i 
Sign up to request clarification or add additional context in comments.

1 Comment

just looking at this again, the 8 character value will be to contain a maximum of 2 letters and maximum of 7 numbers randomly. your above answer i believe only allows letters at the beginning. Is that right?

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.