简体   繁体   English

向laravel中的验证失败消息添加密钥

[英]Add a key to validation failed message in laravel

I am building a json REST API . 我正在构建一个JSON REST API I need to extend the validation library to add a static tag "error":"validation_failed" for all validation failed json output. 我需要扩展验证库 ,为所有验证失败的json输出添加一个静态标签"error":"validation_failed"

    // create the validation rules ------------------------
    $rules = array(
        'firstName'         =>  'required',
        'lastName'          =>  'required',
        'email'             =>  'required|email|unique:users', 
        'reg_type'          =>  'required|in:'.implode(",", $this->types),
        'oauthUId'          =>  'required_if:reg_type,'.implode(",", $this->externalTypes),
        'password'          =>  'required_if:reg_type,email',
        'parentId'          =>  'sometimes|integer|exists:user_accounts,id',
    );

    // do the validation ----------------------------------

    $validator = Validator::make(Input::all(), $rules);

    // check if the validator failed -----------------------

    if ($validator->fails()) {
        // get the error messages from the validator
        return $validator->messages();
    }
    else {
        // validation successful ---------------------------
    }

I checked the laravel/validator.php and found that it should be added to Illuminate\\Support\\MessageBag object. 我检查了laravel / validator.php,发现应该将其添加到Illuminate \\ Support \\ MessageBag对象。

$this->messages->add($attribute, $message);

How to do that by extending the validator class. 如何通过扩展验证器类来做到这一点。

I need the output json like this 我需要这样的输出json

{
"error":
"validation_failed",
"firstName":
"The first name field is required.",
"lastName":
"The last name field is required.",
"reg_type":
"The selected reg type is invalid."
}

You probably can implement your own validator class and add to it: 您可能可以实现自己的验证器类并将其添加到其中:

class MyValidator extends Validator {

    public function passes()
    {
        if ( ! $passes = parent::passes())
        {
            $this->addError('error', 'validation_failed', []);
        }

        return $passes;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM