2

I have to validate the following scenario: "15AB12" Conditions: (1) First element should be 1 + a single digit+ two alphabets + 2 digits. I need to validate this for a textbox. Here's my code. I don't know where i missed!!!

  <label>Username(6):</label>
    <input id='username' type='text'>
    <p id="p2"></p>
    <button id="submit" onclick= "pepe(); return false"">ChecForm</button> 

      <script>
        function pepe(){
       if (!($("#username").val().match(/^1\[a-zA-Z0-9]{5}/)))
      document.write(" true");
      else
      document.write("false");
      }
      </script>
1
  • Please never use the jQuery Validate tag when the question has nothing to do with this plugin. Edited. Commented Apr 17, 2017 at 17:45

1 Answer 1

2

The first issue is that you escaped a [ char, thus, turning a character class into a sequence of chars and evne if you did not do it, [a-zA-Z0-9]{5} would match 5 alphanumeric chars regardless of the order of digits and alphabets, and it would also allow any special chars after them since no end of string anchor is used.

Your regex should look like

/^1[0-9][a-zA-Z]{2}[0-9]{2}$/

See the regex demo

Details:

  • ^ - start of string
  • 1 - a 1 digit
  • [0-9] - any single digit
  • [a-zA-Z]{2} - 2 ASCII letters
  • [0-9]{2} - any 2 digits
  • $ - end of string.

Also, RegExp#test(String) looks preferable when you need to check if a string matches a pattern or not (it does not return an array with match data if a match is found, just true or false).

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

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.