Validate only alphanumeric characters in Laravel

31,758

Solution 1

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.

Solution 2

use laravel rule,

    public function store(Request $request){
    $this->validate($request, ['filename' => 'alpha_dash']);
}

Laravel validation rule for alpha numeric,dashes and undescore

Solution 3

Might be easiest to use the built in alpha-numeric validation:

https://laravel.com/docs/5.2/validation#rule-alpha-num

$validator = Validator::make($request->all(), [
    'filename' => 'alpha_num',
]);

Solution 4

You forgot to quantify the regex, it also wasn't quite properly formed.

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

This will accept empty filenames; if you want to accept non-empty only change the * to +.

Share:
31,758
Alex Lomia
Author by

Alex Lomia

Updated on July 29, 2020

Comments

  • Alex Lomia
    Alex Lomia over 3 years

    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?

  • Alex Lomia
    Alex Lomia over 7 years
    Thanks! it's actually alpha_dash
  • Alex Lomia
    Alex Lomia over 7 years
    Thanks! it's actually alpha_dash
  • Akram Wahid
    Akram Wahid over 7 years
    sorry, i have linked the correct one, but added the wrong one, anyway I modified the code above..
  • Alex Lomia
    Alex Lomia over 7 years
    Thank you, this is the most complete answer of all even with alpha_dash mentioned!