1

I am new to javascript regular expressions.Any-way i want to valiadate a string that matches some conditions

Here are the conditions

1.String contains only 9 characters

2.First two letters must be alphabets.

3.third letter must be '-' this.

4.Remaining 6 letters must be digits

function validateInput(str){
   if(str.length>9){
    alert("Exeeds maximum limit");
  }
}

How can i do the rest of the validations using regex?

2
  • 1
    regex101.com is a nice place to test regexing Commented Nov 14, 2015 at 14:57
  • what did you tried till now? edit your question! Commented Nov 14, 2015 at 15:46

1 Answer 1

5

The following regex matches exactly what you described:

 /^[a-z]{2}-\d{6}$/i

regex101 demo

  • ^ matches the start of string (preventing matches in the middle of the string)
  • [a-z]{2} matches 1 letter, repeated 2 times (thus it matches 2 letters).
  • - matches a literal dash
  • \d{6} matches a digit, repeated 6 times (6 digits).
  • $ matches the end of string.
  • Mode: /i - case-insensitive match. So [a-z] also matches uppercase letters as well.

Code

function validateInput(str){
    if(/^[a-z]{2}-\d{6}$/i.test(str)){
        document.body.innerText += str + "\t- Valid input\n";
    } else {
        document.body.innerText += str + "\t- Invalid input\n";
    }
}

validateInput("xY-123456");
validateInput("abc-12345");

Note: using document.body.innerText as a way to output in the Code Snippet, but it shouldn't be used in your code

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

1 Comment

You saved my time.Thanks a lot buddy:)

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.