Search code examples
laravellaravel-validation

Avoid html tags in laravel string validation


I want to prevent users of using html tags in their username fields when they are registering, how can I do that?

For instance currently I have a user he registered with such username

E7JfyqxE4lsbqQ <html><a href="https://www.apple.com"><img src="https://...../d28/2011/19/93045d3fb9c4.jpg" width="600" height="234" alt="bill"></a> </html>

I just want to allow letters and numbers (a-z, 0-9) that's all.

RegisterController

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'username' => 'required|string|max:255|unique:users|not_exist',
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

Solution

  • If you only want to allow alphanumeric characters, you can use Laravel's built in alpha_num validation.

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'alpha_num', 'max:255'],
            'username' => 'required|string|alpha_num|max:255|unique:users|not_exist',
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }