Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

Regex to require at least 2 letters in string

$pattern = "/[a-z]*[a-z]*/i";
if (!preg_match($pattern, $value)){
    $this->error_name = "The name should contain at least two letters."; 
}

I am trying to check if the user types his name with at least two letters. So basically, he can't enter his name as such 111111111111. it must have two letters.

The regular expression that I wrote doesnt work..why?

Upvotes: 2

Views: 161

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173542

Returns true when at least two alphabets are used in a string:

preg_match_all('/[a-z]/', $str, $m) >= 2;

Upvotes: 1

Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

$pattern="/^([a-z]{2})|([a-z].*[0-9].*[a-z].*).*/i";

I think the answer should be the one above.. your answers gave me a clue..

now it will match also those names:

a1111111111111a

Upvotes: 0

Jeroen
Jeroen

Reputation: 13257

$pattern="/[a-z].*[a-z]/i";
if(!preg_match($pattern, $value)){
   $this->error_name="The name should contain at least two letters."; 
}

Your code didn't work because * means zero or more times, so it would also match none or one character.

Upvotes: 0

codaddict
codaddict

Reputation: 454960

You can use:

$pattern="/^[a-z]{2,}$/i";

This will ensure that the name has only letters and there are at least 2 letters in the name.

Edit:

Looks like you want the name to contain at least two letter and can contain other non-letters as well:

$pattern="/^.*[a-z].*[a-z].*$/i";

Upvotes: 3

Related Questions