Skip to content
Advertisement

Laravel: company validation using regex

I don’t have any idea about how to use regex. I want to validate my company field.

For example:

  1. url.co
  2. url.com
  3. url.in

Right now my PHP script takes any string but I want to validate it according to the website URL which contains

string + . + any domain

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

    ]);
}

Advertisement

Answer

try this:

protected function validator(array $data)
{
    $messages = [
        'company.regex' => 'Invalid format.'
    ];

    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', 'max:255', "regex:/b((http|https)://?)[^s()<>]+(?:([wd]+)|([^[:punct:]s]|/?))/"],
        'username' => ['required', 'string', 'max:255', 'unique:users'],

    ],$messages);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement