2

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'],
    ]);
}
2
  • try to use regex and include in the regex the <> within this role Commented Mar 3, 2021 at 3:27
  • @codeformoney you mean like this? 'name' => ['required', 'string', 'max:255', 'not_regex:<>'], Commented Mar 3, 2021 at 3:28

2 Answers 2

2

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'],
    ]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'username' => [
          'required',
          'string',
          'max:255',
          'string',
          'unique:users',
          'not_exist',
          'not_regex:<\s*a[^>]*>(.*?)<\s*/\s*a>'
        ],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

You can add more regex if you have more to include

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.