Reputation: 239
I have to check for capital letters to exist just at the beginning of words.
My regex now looks like this:
/^([A-ZÁÉÚŐÓÜÖÍ]([a-záéúőóüöí]*\s?))+$/
It's at the words beginning works good, but if the problem not at the beginning of the word it's fails.
For example: John JohnJ
got validated.
What should i alternate in my regex to works well?
Upvotes: 0
Views: 149
Reputation: 5954
You can do this: /^([A-ZÁÉÚŐÓÜÖÍ]{0,1}([a-záéúőóüöí]*\s?))+$/
With {a,b}
, a
is the least amount of characters it will match, whereas b
is the most amount of characters it will match.
If there is ALWAYS going to be a capital letter at the beginning, instead you can simply use: /^([A-ZÁÉÚŐÓÜÖÍ]{1}([a-záéúőóüöí]*\s?))+$/
In this preceding case, {c}
, c
is the exact number of characters it will match.
Here is a resource with good information.
Upvotes: 0
Reputation: 8413
In your regex pattern the space is optional, allowing combinations like JJohn
or JohnJ
- the key is to make it required between words. There are two ways to do this:
Roll out your pattern:
/^[A-ZÁÉÚŐÓÜÖÍ][a-záéúőóüöí]*(?:\s[A-ZÁÉÚŐÓÜÖÍ][a-záéúőóüöí]*)*$/
Or make the space in your pattern required, but alternatively allow it to be the end of line (this allows a trailing space though).
/^(?:[A-ZÁÉÚŐÓÜÖÍ][a-záéúőóüöí]*(?:\s|$))+$/
In both patterns I have removed some superfluous groups of your original and turned all groups into non-capturing ones.
Upvotes: 1