htmlregexvalidation

HTML input pattern attribute won't validate some regex expression


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.


Solution

  • 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 (v flag for Chrome 112+), which prevents meaningless escapes. Yours has one: \'; simply remove the backslash to make the pattern valid. See also Valid with the RegExp u flag, but not with the v flag.

    Also, the last $ is not necessary since 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>