Alex Lomia
Alex Lomia

Reputation: 7225

Validate only alphanumeric characters in Laravel

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?

Upvotes: 13

Views: 50768

Answers (5)

pankaj
pankaj

Reputation: 1906

I checked above solutions but that was not working in my version. My Laravel v. 5.5.

 'address' => "required|regex:/^[0-9A-Za-z.\s,'-]*$/", 

Upvotes: 0

Mohamed Akram
Mohamed Akram

Reputation: 2117

use laravel rule,

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

Laravel validation rule for alpha numeric,dashes and undescore

Upvotes: 11

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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.

Upvotes: 22

Daniel Waghorn
Daniel Waghorn

Reputation: 2985

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

Upvotes: 2

djt
djt

Reputation: 7535

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

Upvotes: 9

Related Questions