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
Laravel validation no space allowed for username
提问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 foobar
without 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
回答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/'