Laravel验证规则 [英] Laravel Validation Rules

查看:90
本文介绍了Laravel验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要Laravel验证规则.我想使用Laravel验证来检查变量.并通过在控制器中返回字符串来显示自定义错误.(我不使用视图,刀片,会话等...我只是返回字符串)

My need is just Laravel validation Rules.I want to use Laravel validation to check variables. and show custom errors by returning string in controller.(I dont use view, blade, session,... I just return string)

if(strlen($username) < 4) return '{"r": "US","msg": "username is short"}';
if(strlen($username) > 64) return '{"r": "UL","msg": "username is long"}';
if(strlen($address) > 200) return '{"r": "A","msg": "wrong address"}';  

我想要这样的东西:

if($validation->username->min has error)
     return 'string:username is short';

if($validation->address->max has error)
     return 'string:address is long';

if($validation->username->unique has error)
     return 'string:username already exists';

推荐答案

看看官方文档 Laravel 中的验证.您不必手动处理所有情况. Validator :: make()将为您生成一个验证器对象.第一个参数会将您的数据作为关联数组.第二个参数将根据需要定义所有规则.作为第三个可选参数,如果您不喜欢默认错误消息,则可以定义其他错误消息.如果出现无效情况,将在 errors()方法中返回.

Have a look at the official documentation of validation in Laravel. You don't have to handle every case manually. Validator::make() will generate a validator object for you. The first parameter will take your data as an associative array. The second argument will define all rules as desired. As a third, optional parameter you may define alternative error messages if you don't like the default ones. The will be returned in the errors() method in case something isn't valid.

$validator = Validator::make($yourDataArray, [
    'username' => 'min:4|max:64|exists:table,username',
    'address' => 'max:64'
], [
    'min' => ':attribute is too short.',
    'exists' => ':attribute already exists.
]);

if ($validator->fails()) {
    return $validator->errors()->all();
}

如果您不想一次获取所有错误的数组,则可以像这样获取每个字段的状态:

If you don't want to get an array with all errors at once, you can get the state of each field like so:

if ($validator->errors()->has('username')) { // Username field is invalid
    return $validator->errors()->first('username'); // Get the first error
}

如果您想知道什么规则完全失败,可以使用类似的方法:

And if you want to know what rule exactly failed, you can use something like that:

if(isset($validator->failed()['username']['Max'])) {
    return 'Username is too long.';
}

这篇关于Laravel验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆