Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Require at least one alpha character

We have a login form that allows you to enter in your user_id or your player_tag. We have a model with the following rules:

protected $rules = ['player_tag' => 'required|unique|min:3|max:15|regex:/^[a-zA-Z0-9_]+$/'];

Is there a way to add a rule that requires the player_tag field to contain at least 1 alpha character (a-zA-Z)?

Upvotes: 6

Views: 1821

Answers (3)

Tim Hysniu
Tim Hysniu

Reputation: 1540

This might help you:

^(?=.*[a-zA-Z]).+$

Here is a working example: https://regex101.com/r/gD3gR6/2

Upvotes: 5

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Try this way

/^\d*[a-zA-Z][a-zA-Z0-9]*$/

Explanation :

1. 0 or More digits;

2. At least 1 character; //this will ensure your at least one alpha condition

3. 0 or 1 alpha numeric characters;

Upvotes: 0

JHoffmann
JHoffmann

Reputation: 727

If there should be one alpha character at the beginning of the field, you can simply extend your regex to check for one such char at the beginning:

/^[a-zA-Z][a-zA-Z0-9_]*$/

To require at least one alpha character without specific position, just use the following regex:

/^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/

Upvotes: 2

Related Questions