gunmen000
gunmen000

Reputation: 33

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

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

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

regex101 link

Any help is appreciated

Upvotes: 3

Views: 657

Answers (1)

vs97
vs97

Reputation: 5859

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

Upvotes: 5

Related Questions