Search code examples
laravel-5laravel-validation

Include global search in Laravel Validation


I want the 'name' attribute only to take alphabetic characters, numbers and spaces. It's all okay. I've tested it on http://regexr.com/ but when I run it using Laravel I get the "preg_match(): Unknown modifier 'g'" error

public function rules()
{
    return
    [
        'name' => ['regex:/([A-Za-z0-9 ])*/g']
    ];
}

I've been searching but all I get is a "use the preg_match_all() method" but how can I do that whithin this?


Solution

  • g is not a valid PCRE modifier in PHP.

    That said, to only permit alphanumeric and spaces, you can use a rule like:

    regex:/^[A-Za-z0-9 ]*$/
    

    ^ indicates the beginning of the string, and $ the end.

    In situations where Laravel's stock rules don't cut it, you also have the option of creating a custom modifier (where you could use preg_match_all to your heart's content).