2

I have the following code:

<body>
    <form action="" method="post">
        <div>
            <label>First Name: <input type="text" name="firstname" value=" " pattern="[a-zA-Z ]+"></input> </label>
        </div>
        <div>
            <label>Last Name: <input type="text" name="lastname" value="" pattern="[a-zA-Z ]+"> </input> </label>
        </div>
        <div>
            <label>Voucher: <input type="text" name="voucher" value="" pattern="^[0-9]{5}+[-]+[0-9]{5}+[-]+[A-Z]{2}*"></input> </label>
        </div>
        <input type="submit" value="Submit"></input>
    </form>
</body>

The above code is my code, first name and last name are all working, the problem is the voucher input does not check the pattern I wanted, it should look like "12345-67890-AB".

2
  • You don't need the + because you are already saying you need 5 characters Commented May 27, 2015 at 10:25
  • 1
    you don't need ^ at the beginning of the regex (nor $ at the end). the pattern attribute of HTML forms implies that Commented May 27, 2015 at 10:58

2 Answers 2

3

Remove the +s and final * and add a $ at the end:

^[0-9]{5}[-][0-9]{5}[-][A-Z]{2}$

Or since the pattern attribute does not require anchoring, you can also use

[0-9]{5}[-][0-9]{5}[-][A-Z]{2}

See demo

Explanation:

  • ^ - Beginning of a string (not necessary since the pattern string is anchored)
  • [0-9]{5} - Exactly 5 digits
  • [-] - Exactly 1 hyphen
  • [0-9]{5} - Exactly 5 digits
  • [-] - Exactly 1 hyphen
  • [A-Z]{2} - Exactly 2 uppercase English letters.
  • $ - End of string (again, can be omitted since the pattern is anchored).
Sign up to request clarification or add additional context in comments.

2 Comments

@iouhammi: This regex is very generic, it will work for JavaScript and most other flavors.
Thank you! this one works as well ! thanks for the explanation too !
2

Try this instead

^[0-9]{5}[-]+[0-9]{5}[-]+[A-Z]{2}

http://regexr.com/3b338

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.