lostbyte
lostbyte

Reputation: 486

Laravel email validation issue

Default Laravel Validation class allows strange emails. Here is the Validation rules that I defined:

return Validation::make($data, [
        'email' => 'required|string|email|max:100|unique:customers,email'
]);

When I tried to use some strange email like: aaaa?#%&'@şğüçi̇ö.com it passes the validation. However the non latin characters on the email is converted before DB insert. So the email address on the database doesn't match with the original one.

In order to prevent this I want to disallow the usage of non-latin characters after the @ symbol. I tried the custom rule which is:

public function passes($attribute, $value)
{
    return filter_var($value, FILTER_VALIDATE_EMAIL) 
    && preg_match('/@.+\./', $value);
}

but it is not working. It would be good to get some help on this.

Edit 1 Thanks for your responses! But apparently the reason that the custom validator not taking action is that Laravel sanitizes all input data before any manipulation. That's why after it converts the non-latin characters, preg_replace() returns 1 all the time since there is no non-latin characters on the input. First of all I need to find a solution to this and prevent Laravel to sanitize the input.

Upvotes: 0

Views: 1001

Answers (1)

Lloople
Lloople

Reputation: 1844

From your question I understand you already created a custom Validation Rule and use it like

...
'email' => [
    'required',
    'string',
    ...
    new ValidateLatinEmail()
]

As you can see here, your RegEx is the problem with that validation

This one should work:

public function passes($attribute, $value)
{
    return filter_var($value, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@[\x00-\x7F]*\./', $value);
}

Upvotes: 1

Related Questions