t0m
t0m

Reputation: 173

PHP Validation for alpha numeric characters

I have the following code for validating user input for alpha numeric characters

if (!preg_match("/^[A-Za-z][A-Za-z0-9.]*(?:_[A-Za-z0-9]+)*$/", $username)){
echo "invalid username";
}

It checks, whether the input have other characters than (A-Z) (0-9) alpha numeric. Additionally it allows to accept (_) underscore also, but it should be placed in between the strings only as my_name, but it will not accept _myname or myname_.

My question is how can I add a dot(.) character in my above code as same as constrained in underscore as Eg accept (my.name) or (myn.ame) etc but not to accept (.myname) (myname.)

Upvotes: 1

Views: 3961

Answers (1)

Dale
Dale

Reputation: 10469

I think this pattern should work for you

$string = 'my_nam.e';
$pattern = '/^[a-z]+([a-z0-9._]*)?[a-z0-9]+$/i';
if ( ! preg_match($pattern, $string))
{
    echo 'invalid';
}

Upvotes: 2

Related Questions