I am trying to make an input with regex for the following pattern:
- Force start first character with a capital letter
- Force first character of other WORDS (letters) capital letter
- Force all other letters in words lowercase
- Allow numbers & special characters anywhere except 1st character of words
<input type="text" name="display_name" placeholder="Display Name" id="display_name" required minlength="1" maxlength="32"
pattern="[A-Z].{1,1}[a-z1-9W_]).{,}[ ]{,}[A-Z].{1,1}[a-z1-9W_]).{,}[ ]{,}[A-Z].{1,1}[a-z1-9W_]).{,}[ ]{,}">
Also, if you can do this pattern, can I also get the same pattern to use for php pregreplace.
2
Answers
As pointed out in the comments, the older regex has some problems. So, you can try this new regex.
This is a fiddle showing some test cases.
And here is the PHP in which this regex can be used.
And if you want to convert this into function, then try following:
And, if you want to use Javascript to force the input to follow the regex, you can try the following:
And the
error_message
is just a span. Also, after this Javascript, I don’t think you would need thepattern
thing in your input. So, if you are using this Javascript, you can remove thepattern
from your input.Hope this helps.
When using PHP, you could use:
The regex in parts matches:
^
Start of string[A-Z]
Match an uppercase char A-Z[^A-Zs]*
Match 0+ times any character except an uppercase char A-Z or a whitespace char(?:
Non capture group to repeat as a whole parth+
Match 1+ horizontal whitespace chars[A-Z][^A-Zs]*
Match a char A-Z and 0+ times any character except an uppercase char A-Z or a whitespace char)*
Close the non capture group and optionally repeat$
End of stringSee a regex demo.
For Javascript you could slightly change the regex to:
See another regex demo