I think the issue can be due to the characters you declared in the
character classes. According to some changes to the regex flavor
in JavaScript, the u or v flag may be enabled (it seems
to be hard-coded or automatically triggered and cannot be set
manually) and this can cause problems in character classes. For
example, [a-z|]
has |
which should now be escaped with \|
also
in a character class. You're using some in your pattern.
I would not use \w
but replace it by \p{L}
which is used to match
any letter in any language. This will match "é" or "ÿ" and not only
English letters without accents.
It's rather complicated to match all the correct cases, but this is
what I can suggest:
^(?:\p{L}['´ \-]?)+(?<=[^\s\-'´])$
The idea is to accept an input starting with a letter and then
followed by an optional space, hyphen or '
or ´
, one or multiple
times. To avoid finishing with a space or one of those chars, you
can add a positive lookbehind just before the end of the pattern.
This will avoid accepting something like Jack-
or Ooooh'
.
The other advantage is that you can't accept Jean--Jaques
or
O''Neil
.
form {
margin: 1em;
padding: 0;
display: flex;
column-gap: 1em;
}
input {
padding: 0.25em .5em;
border: 1px solid gray;
}
input[type="text"] {
box-shadow: 1px 1px 4px inset rgba(0, 0, 0, 0.1);
}
input[type="text"]:focus {
outline: 1px solid gray;
}
input[pattern]:focus:valid {
border-color: green;
}
input[pattern]:focus:invalid {
border-color: red;
}
input[type="submit"] {
background-color: silver;
}
:focus-visible {
outline: none;
}
<form action="#">
<div class="form-element">
<input
name="firstName"
pattern="^(?:\p{L}['´ \-]?)+(?<=[^\s\-'´])$"
title="Your first name must be valid"
type="text"
placeholder="First Name"
required
/>
</div>
<div class="form-element form-submit">
<input type="submit" value="Submit" />
</div>
</form>
You can also test the regex with examples and the explanation
here: https://regex101.com/r/tmEsgX/2
` or `
` tag depending on the [doctype](https://www.w3schools.com/tags/tag_doctype.asp). I think it will only be invalid with HTML 4.01. Now that we are often using HTML 5, it won't be a problem. It can just be some sugar for readability, make it more compatible with XML parsers, and perhaps also help some old color highlighting tools work better. But yes, `` is bad! – Patrick Janser Aug 22 '23 at 15:21