我正在构建 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."
}
答案 0 :(得分:1)
您可能可以实现自己的验证器类并添加到它:
class MyValidator extends Validator {
public function passes()
{
if ( ! $passes = parent::passes())
{
$this->addError('error', 'validation_failed', []);
}
return $passes;
}
}