Reputation: 538
I need the username to be either alpha
or alpha_num
.
Validator::make($data, [
'username' => 'alpha|alpha_num',
]);
Upvotes: 0
Views: 715
Reputation: 147
Why not just use alphanum (since apha is a subset of alphanum).
alphanum will validate true when all alpha chars, all numeric chars, or mix of alpha and numeric chars.
If you are wanting to exclude the all numeric possibility (i.e. validate true when all alpha chars or a mix of alpha and numeric chars, but not when all numeric) then you can use a regular expression
Validator::make($data, [
'username' => 'regex:/^(?![0-9]*$)[a-zA-Z0-9]+$/'
]);
But to answer your first question about how to make an OR in validation rules, you will need to make your own custom rule.
Check out the documentation on custom validation rules https://laravel.com/docs/5.6/validation#custom-validation-rules
If it's something you're going to use again you're better off to write a rule. If it's a one time thing then you can put it in a closure.
As an example using a closure, if you wanted to test for alpha with ctype_alpha() and test for alphanumeric with ctype_alnum(), then you could do an OR like
Validator::make($data, [
'username' => [
function($attribute, $value, $fail) {
if( ctype_alpha($value) || ctype_alnum($value)) {
return $value;
}
return $fail($attribute.' is invalid.');
}
]
]);
Upvotes: 1
Reputation: 21681
You can Use the below validation to solve your issue.
$this->validate($request, ['fieldname' => 'regex:/^[\w-]*$/']);
Upvotes: 2
Reputation: 8287
You can try
Validator::make($data, [
'username' => 'alpha_dash',
]);
The field under validation may have alpha-numeric characters, as well as dashes and underscores.
details https://laravel.com/docs/5.6/validation#rule-alpha-dash
Upvotes: 0