Validate only alphanumeric characters in Laravel

Alex Lomia picture Alex Lomia · Jul 28, 2016 · Viewed 24.6k times · Source

I have the following code in my Laravel 5 app:

public function store(Request $request){
    $this->validate($request, ['filename' => 'regex:[a-zA-Z0-9_\-]']);
}

My intentions are to permit filenames with only alphanumeric characters, dashes and underscores within them. However, my regex is not working, it fails even on a single letter. What am I doing wrong?

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Jul 28, 2016

You need to make sure the pattern matches the whole input string. Also, the alphanumeric and an underscore symbols can be matched with \w, so the regex itself can be considerably shortened.

I suggest:

'regex:/^[\w-]*$/'

Details:

  • ^ - start of string
  • [\w-]* - zero or more word chars from the [a-zA-Z0-9_] range or -s
  • $ - end of string.

Why is it better than 'alpha_dash': you can further customize this pattern.