Reputation: 704
I have no idea how to make validation rules for the email field. I want to accept mail id which are not from server say '@myemail.com, @yahoo.com, @outlook.com' when someone is registering. If this mail address is given it will say your mail id is not valid. what should I do??
please help me, here is my ResigterController.php
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'mobile_no' => ['required', 'string', 'min:10'],
'company' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users'],
]);
}
and I don't have email.php in my config directory.
Upvotes: 3
Views: 6482
Reputation: 342
Better to use config file seprated for example config\settings.php
<?php
return [
'restricted_email_domains'=>[
'myemail.com', 'yahoo.com', 'outlook.com',
],
];
so, your code would be
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users',
function ($attribute, $value, $fail) {
if (in_array($value, config('settings.restricted_email_domains')))
{
$fail('The '.$attribute.' is invalid.');
}
},
],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'mobile_no' => ['required', 'string', 'min:10'],
'company' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users'],
]);
}
Reference using-closures
Upvotes: 0
Reputation: 15786
You could add a regex validation on top of that.
$rules = [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
'unique:users',
'regex:/^\w+[-\.\w]*@(?!(?:outlook|myemail|yahoo)\.com$)\w+[-\.\w]*?\.\w{2,4}$/'
],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'mobile_no' => ['required', 'string', 'min:10'],
'company' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users'],
];
// Add a custom message for regex validation on email field.
$messages = [
'email.regex' => 'We do not accept mails with this domain.'
];
Validator::make($data, $rules, $messages);
I adapted the regex from a reply to another question. The regex should work according to regex101.com.
Another option is to make your own validation rule. Refer to the documentation for that.
Upvotes: 1