Search code examples
htmlreactjsforms

HTML5 input tag regex check saying regex is invalid


I'm trying to add regex validation to my input tag. Here's a code example:

<input name="password" pattern="^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$"/>

This regex works fine at https://regex101.com , I'm even using it in my backend to validate the value passed from this input tag. HTML5 just seems to hate it.

I've checked other answers, which mentioned to not escape somethings. I'm not escaping anything.


Solution

  • Pattern

    1. (?=.*?[A-Z]): Checks if the password contains at least one uppercase letter.
    2. (?=.*?[a-z]): Checks if the password contains at least one lowercase letter.
    3. (?=.*?[0-9]): Checks if the password contains at least one numeric digit.
    4. (?=.*?[#?!@$%^&;*\-]): Checks if the password contains at least one of the following special characters: #?!@$%^&;-.
    5. .{8,}: Checks if the password has a minimum length of 8 characters.

    Explanation

    • The pattern is always anchored by default, you need no ^ and $ anchors.
    • In the pattern (?=.*?[#?!@$%^&;*\-]), the backslash \ is used before the hyphen - to escape the character. The hyphen has a special meaning within a character class in a regular expression. It is used to indicate a character range. To treat the hyphen as a literal character within a character class, you need to escape it with a backslash \. This instructs the regular expression to interpret the hyphen as a normal character instead of a range indicator.

    I tested it like this and seems work fine:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Page Title</title>
      </head>
    
      <body>
        <form>
          <label for="username">Username</label><br />
          <input
            name="username"
            id="username"
            pattern="(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&;*\-]).{8,}"
          />
        </form>
      </body>
    </html>