【问题标题】:Add a key to validation failed message in laravel在 laravel 中添加验证失败消息的密钥
【发布时间】:2014-11-21 15:21:41
【问题描述】:

我正在构建一个 json REST API。我需要扩展验证库,为所有验证失败的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 ---------------------------
    }

我检查了 laravel/validator.php,发现应该添加到 Illuminate\Support\MessageBag 对象中。

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

如何通过扩展验证器类来做到这一点。

我需要这样的输出 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."
}

【问题讨论】:

    标签: php laravel laravel-4 laravel-validation


    【解决方案1】:

    您可能可以实现自己的验证器类并添加到它:

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

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 2021-07-04
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2013-07-08
      • 2021-12-25
      • 2013-02-16
      • 1970-01-01
      相关资源
      最近更新 更多