Model Rules() + Regex!

Hello guys!

I’m trying to set a regex pattern on model rules for my username property. I just want to allow the user to use alpha-numeric characters and dots, but the username can not start/end with a dot/symbol and can not have two or more dots together.

Some examples that I don’t want to happen

.

8…

0.8 9…

#…Jhon

.Jhon

Jhon-

jhon-.

.Jhon.

jh…in

89.jhon.-

jhon-0,78#

Some examples that are allowed

jhon.78

78.jhon.2

jhon.ma

jhon

78jhon

jhon89

I have tried to create a regex but without complete success. Does someone can give me some tips about it!? The regexp I have so far is




/^[a-z0-9]+([a-z0-9]+[\.]?)+$/i



but for some reason is giving me problems in some cases, like this "a.aaa". Any ideas about the correct regex?

Assuming that Yii allows you to use more than one regular expression validator for the same attribute, I’d split it up for clarity:




    // Reject if starts or ends with a dot, or if has two or more dots in a row

    array('username', 'match', 'pattern'=>'/^\.|\.{2,}|\.$/', 'not'=>true),

    // Accept if comprised of alphanumeric characters and dots

    array('username', 'match', 'pattern'=>'/^[a-z0-9\.]+$/i', 'skipOnError'=>true),



You might need to tweak the patterns, I’ve not used regular expressions in a while.

1 Like

Nice idea Keith. I’m gonna check that.