Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate email domain in Laravel request

I want to accept email from just one server when someone is registering, for example "@myemail.com". If any other email address is given it will say your email is not valid.

Below is the validator of my registration controller. What should I do?

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
        /*'usertype' => 'required',*/
    ]);
}
like image 280
incorporeal Avatar asked Jan 30 '17 09:01

incorporeal


3 Answers

You could use a regex pattern for this. Append this to your email validation:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|regex:/(.*)@myemail\.com/i|unique:users',
        'password' => 'required|min:6|confirmed',
        /*'usertype' => 'required',*/
     ]);
}

EDIT
With mutiple domains you have to use an array with your validations, because of the pipe between the two mail domains:

'email' => ['required', 'max:255', 'email', 'regex:/(.*)@(mrbglobalbd|millwardbrown)\.com/i', 'unique:users'],

Note: 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.

like image 121
Sebastian Avatar answered Oct 14 '22 22:10

Sebastian


since laravel 5.8.17 ends_with validation rule was added, which looks like this:

$rules = [
    'email' => 'required|ends_with:laravel.com,jasonmccreary.me,gmail.com',
];
like image 41
Miloud BAKTETE Avatar answered Oct 14 '22 23:10

Miloud BAKTETE


Please do the following change in your email validation line. You can expand the email validation in your validator rule like:

protected function validator(array $data){
  $messages = array('email.regex' => 'Your email id is not valid.');

  return Validator::make($data, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users|regex:/(.*)\.myemail\.com$/i',
    'password' => 'required|min:6|confirmed',
    /*'usertype' => 'required',*/
 ], $messages);}
like image 43
Nikunj Kabariya Avatar answered Oct 14 '22 21:10

Nikunj Kabariya