Search code examples
htmlregexformsvalidation

HTML form validation with the “pattern” attribute


I am trying to come up with a valid pattern for an HTML form. I would like to allow *@student.*.edu.vn

This is my code:

 <input 
       type="text" 
       name="mail"  
       pattern="([a-z]|[0-9])+(@{1})+(student)+(.)+[a-z]+(.edu.vn)"
   />

It does not work as I would like. What I am doing wrong?


Solution

  • The pattern (regular expression) is slightly wrong as you haven't escaped all your special characters such as the . and have some unnecessary parts within it. Try using the following slightly modified pattern instead:

    ([a-z]|[0-9])+@student\.[a-z]+\.edu\.vn

    <form>
      <input type="text" name="mail" pattern="([a-z]|[0-9])+@student\.[a-z]+\.edu\.vn" />
      <input type="submit">
    </form>

    Note: Make sure that you also do validation on the server-side as anyone entering values into a form can remove the pattern to bypass this check.