Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow alpha characters, space, dash, apostrophe and length <= 50

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.

like image 726
espresso_coffee Avatar asked Dec 19 '25 14:12

espresso_coffee


1 Answers

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.

like image 50
Wiktor Stribiżew Avatar answered Dec 22 '25 04:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!