Validate only alphanumeric characters in Laravel
Asked Answered
P

5

13

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?

Paryavi answered 28/7, 2016 at 20:50 Comment(4)
Try 'regex:/^[a-zA-Z0-9_-]*$/' or just 'regex:/^[\w-]*$/'.Spitz
@WiktorStribiżew It works! Thanks, but what was my mistake?Paryavi
The point is that the whole string should match.Spitz
The mistake, for the record, was a lack of pattern delimiters (/.../) and anchors (^...$).Malik
K
22

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.

Kalynkam answered 28/7, 2016 at 20:57 Comment(1)
Thank you, this is the most complete answer of all even with alpha_dash mentioned!Paryavi
M
11

use laravel rule,

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

Laravel validation rule for alpha numeric,dashes and undescore

Melanism answered 28/7, 2016 at 20:54 Comment(2)
Thanks! it's actually alpha_dashParyavi
sorry, i have linked the correct one, but added the wrong one, anyway I modified the code above..Melanism
K
9

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',
]);
Knotts answered 28/7, 2016 at 20:53 Comment(1)
Thanks! it's actually alpha_dashParyavi
A
2

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

Adorl answered 28/7, 2016 at 20:53 Comment(0)
T
0

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,'-]*$/", 
Thormora answered 4/4, 2022 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.