Norman
Norman

Reputation: 6365

preg_match accept 0 characters or between 50 to 100

I'm trying to write a regex that'll accept a blank string, or, if the string isn't blank it should be between 50 to 100 characters. So the user can submit a blank field, or if he chooses to fill in data, that data should to be between 50 to 100 characters.

How do I add that to the regex below?

preg_match('/^[a-z0-9\s]{50,100}$/i',$str)

Upvotes: 1

Views: 493

Answers (3)

Stephanie Temple
Stephanie Temple

Reputation: 351

I would first trim() it, then apply your rule-set to the input, like remove multi (spaces|tab|etc) within the input, then validate the input, that way you end up with what you want, or return the form and let them fix their input.

Upvotes: -1

Matt.G
Matt.G

Reputation: 3609

Try Regex: ^(?:[a-z0-9 ]{50,100})?$

Demo

Upvotes: 6

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

Try using ^$ with an alternation added to your current pattern:

preg_match('/^$|^[a-z0-9\s]{50,100}$/i', $str)

I have tested this and empty string is accepted. Otherwise, the only way to match would be for the input have 50 to 100 alphanumeric/whitespace characters.

Upvotes: 1

Related Questions