Regex for HTML name input validation is not working

Viewed 158

I want to use this pattern /^[a-zA-ZÀ-ÖØ-öø-ÿ+\.+\- ]+$/i to validate names in <input> fields. But in the HTML validation this does not work. I used pristine.js before and in there it worked without any problem.

I also created a JS Fiddle: https://jsfiddle.net/3et69oz8/:

<form>
  <input id="first name" name="first_name" required
  pattern="/^[a-zA-ZÀ-ÖØ-öø-ÿ+\.+\- ]+$/i">
  <button>Submit</button>
</form>

1 Answers

First of all, you need to use a string regex pattern, not a regex literal in the HTML pattern attribute, and you do not have to use the case insensitive modifier as the a-zA-Z and À-ÖØ-öø-ÿ ranges include both lower- and uppercase letters.

Next, you are using ^ and $ anchors, but the HTML pattern attribute anchors the match by default, it compiles the pattern with ^(?: in front and )$ at the end of the given pattern string. So, they are redundant here. Same as one of the +, or both, it is not clear if you want to allow the + symbol or not in the user input. If you do, just keep one occurrence.

Moreover, you do not need to escape the . inside square brackets, and - can be moved to the end of the character class so that you do not have to escape it.

So, you can use

<form>
  <input id="first name" name="first_name" required pattern="[a-zA-ZÀ-ÖØ-öø-ÿ.+ -]+">
  <button>Submit</button>
</form>

Details:

  • ^(?: (added implicitly) - start of string and start of the non-capturing group
  • [a-zA-ZÀ-ÖØ-öø-ÿ.+ -]+ - one of the chars specified in the character set/ranges. Note the +, remove if users are not allowed to input it.
  • )$ (added implicitly) - end of the group and string.
Related