Laravel 验证器之条件验证 sometimes

案例

今天遇到两个情景:

  • 添加用户时需要验证密码必填,但是编辑用户时不需要验证密码必填。
  • 邮箱输入时需要验证邮箱格式以及表内邮箱唯一。

翻了翻手册,找到一个sometimes的验证方法
Validation - Laravel 按条件增加规则

代码

 'required'
        ];
    }

    protected function getValidatorInstance()
    {
        $validator = parent::getValidatorInstance();
        $validator->sometimes('password', 'required', function ($input) {
            # 判断id,决定是否启用验证规则
            if (!isset($input->id) || empty($input->id)) {
                return $input;
            }
        });
        $validator->sometimes('repassword', 'required|same:password', function ($input) {
            if (!isset($input->id) || empty($input->id)) {
                return $input;
            }
        });
        $validator->sometimes('email', [
            'required',
            'email:rfc,dns',
            Rule::unique('users')->ignore(request('id'))->where(function ($query) {
                $query->whereNull('deleted_at');
            }),
        ], function ($input) {
            if (!isset($input->email) || empty($input->email)) {
                return $input;
            }
        });
        return $validator;
    }
}

示例参数

{
    "name": "张三",
    "password": "",
    "repassword": "",
    "email": "[email protected]"
}

返回示例

{
    "message": "The given data was invalid.",
    "errors": {
        "password": [
            "The password field is required."
        ],
        "repassword": [
            "The repassword field is required."
        ],
        "email": [
            "The email has already been taken."
        ]
    },
    "status_code": 422
}

仅记录laravel小技巧,文内验证规则均简写。

你可能感兴趣的:(Laravel 验证器之条件验证 sometimes)