Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Combination for accepting only word or only letters for laravel validation

Tags:

regex

laravel

Im having difficulty constructing a regex validation for laravel that accepts only characters or only digits. It goes something like this:

  • Hello <- ok
  • 123 <- ok
  • hello123 <-not ok

my regex right now is something like this: [A-Za-z]|[0-9].

regex101 link

Any help is appreciated

like image 214
gunmen000 Avatar asked Jan 23 '26 07:01

gunmen000


1 Answers

Take a look at this Regex:

^[a-zA-Z]+$|^[0-9]+$

Regex Demo

You were close, but you must add the start of line ^ and end of line $ tags, as well as the + to match at least 1 to unlimited times.

Explanation:

^            # start of line
[a-zA-Z]+    # match a-zA-Z recursively
$            # end of line
|            # OR
^            # start of line
[0-9]+       # match [0-9] recursively
$            # end of line

Bonus:

If you have a block text and you want to extract matches that are either only letters or only digits, instead of start and end characters you can use word boundaries:

\b[a-zA-Z]+\b|\b[0-9]+\b

Regex Demo

like image 53
vs97 Avatar answered Jan 25 '26 01:01

vs97