I'm trying to write regular expression that allows alpha characters, space, dash, apostrophe and length 50. So far I have this:
/^([A-Za-z\s].{1,50})$/
I'm not sure where I should place the code for dash and apostrophe. If anyone can help pleases let me know. Thanks.
You need
/^[A-Za-z '-]{1,50}$/
or
/^[A-Za-z\s'-]{1,50}$/
When you use \s instead of a space, you will allow any whitespace.
The apostrophe can be placed anywhere inside the character class (so as not to ruin the ranges), and the hyphen at the start/end of the character class does not need to be escaped.
If you use {1,50} limiting quantifier, it means you allow 1 to 50 chars of the type specified in the character class. If you allow exactly 50 chars, use /^[A-Za-z\s'-]{50}$/. If you use just + instead, you will allow 1 or more characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With