【问题标题】:Laravel Request Validation Custom Function with multiple attributes具有多个属性的 Laravel 请求验证自定义函数
【发布时间】:2021-09-27 01:56:51
【问题描述】:

我目前正在从事一个投标需要填写 API 凭据的项目。我想在保存之前确保凭据正常。

我想制定一个自定义验证规则,使用用户名和密码来调用 API,以检查凭据是否正常。我可以将验证规则添加到 api_username,但是由于受保护的 $validator->data 属性,我无法获取密码。

谁能帮我解决这个问题?

public function rules()
{
    return [
        'title' => 'required|string',
        'api_username' => 'required|string|min:32|max:32|api_cred_check',
        'api_password' => 'required|string|min:32|max:32',
    ];
}

public function withValidator($validator)
{
    $validator->addExtension('api_cred_check', function ($attribute, $value, $parameters, $validator) {
        //Use credentials to make call to API.
    });

    $validator->addReplacer('api_cred_check', function ($message, $attribute, $rule, $parameters, $validator) {
        //Message if Username and Password won't match.
    });
}

【问题讨论】:

  • 在验证器中,您必须验证字段,而不是检查信用。

标签: laravel validation request


【解决方案1】:

你也可以像这样使用 clouser 作为自定义验证

public function rules()
{
    return [
        'title' => 'required|string',
        'api_username' => ['required', 'string', 'min:32', 'max:32', function ($attr, $value, $fail) {
            // You can use guzzle Http here to make an API call 
        }],
        'api_password' => ['required', 'string', 'min:32', 'max:32', function ($attr, $value, $fail) {
            // You can check if Username and Password is wrong.
        }],
    ];
}

使用最后一个参数 $fail 作为函数 $fail('With your desired message if validation failed.');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2020-05-20
    • 2015-09-24
    相关资源
    最近更新 更多