Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel,valdiation alpha_破折号防止破折号_Php_Laravel - Fatal编程技术网

Php Laravel,valdiation alpha_破折号防止破折号

Php Laravel,valdiation alpha_破折号防止破折号,php,laravel,Php,Laravel,我有一个验证规则: $rules = ['username' => 'required|string|alpha_dash'] 我需要防止破折号验证,只允许下划线、字母和数字。我怎么能做到?现在alpha_dash允许破折号..如果您愿意,我建议使用regex验证来获得更多的定制功能。看 或者更具体地说 $rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_]+$/'] 因为根据文档alpha_-dash支持- 验

我有一个验证规则:

$rules = ['username' => 'required|string|alpha_dash']

我需要防止破折号验证,只允许下划线、字母和数字。我怎么能做到?现在alpha_dash允许破折号..

如果您愿意,我建议使用
regex
验证来获得更多的定制功能。看

或者更具体地说

$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_]+$/']
因为根据文档
alpha_-dash
支持-

验证中的字段也可能包含字母数字字符 as短划线和下划线


您可以在验证中使用
regex:pattern

$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_.]+$/']

除了其他答案之外,您还可以创建自定义的
验证规则

下面的artisan命令将在
app\Rules\
文件夹中创建新规则

php artisan make:rule AlphaNumeric
字母数字

class AlphaNumeric implements Rule
{
    public function passes($attribute, $value)
    {
        return preg_match('/^[A-Za-z0-9_]+$/', $value);
    }

    public function message()
    {
       return 'your custom error message.';
    }
}
控制器

$rules = [
    'username' => ['required', 'string', new AlphaNumeric()]
]

这种方法可以用来创建更复杂、更灵活的验证。

我已经为您添加了答案,它有用吗?如果是的话,请看这里
$rules = [
    'username' => ['required', 'string', new AlphaNumeric()]
]