Validate only alphanumeric characters in Laravel

余生长醉 提交于 2019-12-03 06:46:42

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.

use laravel rule,

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

Laravel validation rule for alpha numeric,dashes and undescore

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!