'How can I validate "Username" field in Laravel to contain letters, numbers, underscores and dashes?

public function store()
{
$this->validate(request(),[
// Third try
‘username’ => ‘required|string|regex:/\w*$/|max:255|unique:users’,
// Second try
‘username’ => ‘required|string|regex:/^[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)*$/|max:255|unique:users‘,
// First try 
’username’ => ‘required|string|max:255’,
]);
}

The username field was working well with numbers included (at first try) but then I forgot to include “unique:users”, then the form started rejecting it (redirects back with username field underlined with wriggle red line). Plus I have used laravel’s “alpha_dash” several times but keeps rejecting the input. My aim is mixture of letters, numbers, underscores and dashes.

Some please help me make this right. Thanks



Solution 1:[1]

When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character :

public function store(Request $request)
{
    $validatedData = $request->validate([
        'username' => 
          array(
            'required',
            'unique:users,username',
            'max:255',
            'regex:/\w*$/'
          )
    ]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1