Search code examples
phpregexlaravelemail-validationlaravel-6

Laravel: validation for email


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'],

    ]);
}

controller.php

config.php

and I don't have email.php in my config directory.


Solution

  • 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.