Reputation: 577
I have validation rule:
$rules = ['username' => 'required|string|alpha_dash']
I need prevent dash in validation, allow only underscores, letters and numbers. How I can do it? Now alpha_dash allow dashes..
Upvotes: 4
Views: 9694
Reputation: 11
Try this rule instead of alpha_dash
[
'username' => ['regex:/^[0-9a-zA-Z_\-]*$/']
]
Upvotes: 1
Reputation: 4499
Aside from the other answers, You can create custom validation rule
following artisan command will create a new rule in the app\Rules\
folder.
php artisan make:rule AlphaNumeric
AlphaNumeric
class AlphaNumeric implements Rule
{
public function passes($attribute, $value)
{
return preg_match('/^[A-Za-z0-9_]+$/', $value);
}
public function message()
{
return 'your custom error message.';
}
}
Controller
$rules = [
'username' => ['required', 'string', new AlphaNumeric()]
]
This approach can be use to create more complex and flexible validations.
Upvotes: 2
Reputation: 38502
I would suggests to use regex
validation to get more power to customize in future if you wish. SEE https://laravel.com/docs/5.8/validation#rule-regex
'regex:/^[A-Za-z0-9_]+$/'
or more specifically
$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_]+$/']
Because as per documentation alpha_dash
supports-
The field under validation may have alpha-numeric characters, as well as dashes and underscores.
Upvotes: 7
Reputation: 1807
You can use regex:pattern
in your validation.
$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_.]+$/']
Upvotes: 3