skip to Main Content

I have an an email type input which has an email validation pattern attribute set up that doesn’t seem to trigger as expected.

<form>
  <input type="email" placeholder="enter your email" pattern="[A-Za-z0-9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$" required>
  <button>submit</button>
</form>

It’s kind of weird cause part of it works. The regex exp is supposed to be matched only after some text and a dot and some text again is added after the @ sign. But is also matched instead with no dot and characters after a someText@sometext pattern. I’ve tested it on some online tools like regextester and works fine.

3

Answers


  1. try this:
    add ^ before the pattern

    <form>
      <input type="email" placeholder="enter your email" pattern="^[A-Za-z0- 9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$" required>
      <button>submit</button>
    </form>
    
    Login or Signup to reply.
  2. According to the docs:

    If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

    <input type="email"> | MDN

    The specified pattern is compiled with the u flag, which prevents meaningless escapes. Yours has one: '; simply remove the backslash to make the pattern valid.

    Also, the last $ is not necessary as HTML adds it by default, as with ^.

    Try it:

    input:invalid {
      outline: 1px solid red;
    }
    <form>
      <input
        type="email"
        placeholder="enter your email"
        pattern="[A-Za-z0-9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}"
        value="someText@sometext"
        required
      >
      <button>submit</button>
    </form>
    Login or Signup to reply.
  3. Interesting question, as there are not many similar reports.

    Here is the console log from DevTools.

    12:13:04.218 example.html:1 Pattern attribute value [A-Za-z0-9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[A-Za-z0-9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$/v: Invalid escape
    

    MDN – Regular Expressions – Character class.

    "… In addition to ] and , the following characters must be escaped in character classes if they represent literal characters: (, ), [, {, }, /, -, |. This list is somewhat similar to the list of syntax characters, except that ^, $, *, +, and ? are not reserved inside character classes …"

    So, escaping is not required for the apostrophe, '.

    [A-Za-z0-9._+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search