Reputation: 500
I have a javascript regex against a text area in an html form. Here's the regex:
regex = /[EePp]+/
I would like to also use the regex to check the length of the string in the text area and to have it to be limited to a single character.
I tried
regex = /[EePp]{1}/
And it validates regex to only those characters, but still allows strings of more than one character in the text area:
<input type='text' onkeypress='validate(event)'>
Is it possible to do that through the regex?
Upvotes: 1
Views: 81
Reputation: 9500
If you add anchors, ^
and $
at the start and end of your regex, this will limit it to matching only the pattern and nothing else against the full extent of what is being searched.
So, /^[EePp]{1}$/
-- That says [EePP] at the very beginning of what is being searched,^
, and there is nothing between it and the end, $
, of what is being searched.
Turns out that in this case you don't need the {1}
, because the anchors are telling it exactly how far the match extends. So:
/^[EePp]$/
should do it.
Upvotes: 2