Laravel 验证用户名不允许有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37802457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:25:01  来源:igfitidea点击:

Laravel validation no space allowed for username

validationlaravel

提问by fzlrhmn

I have a little problem in laravel validation request. I want to reject username with space like foo bar. I just want to allow foobarwithout space. Right now my rule is required|unique:user_detail,username. What rule should i use? thanks

我在 Laravel 验证请求中遇到了一个小问题。我想拒绝像foo bar. 我只想允许foobar没有空间。现在我的规则是required|unique:user_detail,username。我应该使用什么规则?谢谢

回答by huuuk

Why don't you use alpha_dashrule?

你为什么不使用alpha_dash规则

required|alpha_dash|unique:user_detail,username

From the documentation:

从文档:

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

验证中的字段可能包含字母数字字符以及破折号和下划线。

And it doesn't allow spaces.

它不允许空格。

回答by scrubmx

You can extend the validator with your own custom rules:

您可以使用自己的自定义规则扩展验证器:

Validator::extend('without_spaces', function($attr, $value){
    return preg_match('/^\S*$/u', $value);
});

Then just use as any other rule:

然后就像任何其他规则一样使用:

required|without_spaces|unique:user_detail,username

Checkout the docs on custom validation rules:

查看自定义验证规则的文档:

https://laravel.com/docs/5.2/validation#custom-validation-rules

https://laravel.com/docs/5.2/validation#custom-validation-rules

回答by Aruna Warnasooriya

You should use regular expression with your validation.

您应该在验证中使用正则表达式。

PHP :

PHP :

required|unique:user_detail,username,'regex:/\s/'