Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regex to allow for alphabetic characters, hypens, underscores, spaces, and numbers

I would like to validate using Laravel for a unique situation. The field I am authorizing is the name of a book. So it can have alphabetic characters, numeric characters, spaces, and hypens/underscores/any other key. The only thing I don't want it to have is spaces at the beginning, before you enter any key. So the name can't be " L", notice the space, whereas "L L L" is completely acceptable. Could anyone help me in this situation?

So far I got a regex validation as such:

regex:[a-z{1}[A-Z]{1}[0-9]{1}]

I'm unsure how to include the other restrictions.

like image 450
Muhammad Avatar asked Oct 19 '25 13:10

Muhammad


1 Answers

  • Short answer :

For alpha_num with spaces use this regEx :

'regex:/^[\s\w-]*$/'
  • Bit longer one :)

Here is some defined bolcks of regEx :

^           ==>  The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted
$           ==>  Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
.           ==>  The period matches any single character
?           ==>  It will match the preceding pattern zero or one times
+           ==>  It will match the preceding pattern one or more times
*           ==>  It will match the preceding pattern zero or more times
|           ==>  Boolean OR
–           ==>  Matches a range of elements
()          ==>  Groups a different pattern elements together
[]          ==>  Matches any single character between the square brackets
{min, max}  ==>  It is used to match exact character counts
\d          ==>  Matches any single digit
\D          ==>  Matches any single non digit character
\w          ==>  Matches any alpha numeric character including underscore (_)
\W          ==>  Matches any non alpha numeric character excluding the underscore character
\s          ==>  Matches whitespace character

And if you want to add some other chars all you should do is add it to the [] block.

For example if you want allow the , ==> 'regex:/^[\s\w-,]*$/'.

PS : One more thing if you want a setial char such us \ * or . you must escape them like this \ * .

For * ==> 'regex:/^[\s\w-,\*]*$/'

like image 191
Maraboc Avatar answered Oct 22 '25 04:10

Maraboc



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!