验证规则:
public function rules()
{
return [
[['name', 'email', 'password'], 'required'],
[['email'], 'unique'],
[['password'],'string', 'min' => 6],
];
}
方案
public function signup() {
if (!$this->validate(array('name')) {
$register_errors['field'] = 'name';
$register_errors['message'] = $this->getErrors('name');
}
if (!$this->validate(array('email')) {
$register_errors['field'] = 'email';
$register_errors['message'] = $this->getErrors('email');
}
if (!$this->validate(array('password')) {
$register_errors['field'] = 'password';
$register_errors['message'] = $this->getErrors('password');
}
}
返回值
if (!$this->validate) {
$register_errors['error'] = true;
return json_encode($register_errors);
}
结果: 总是回来
{"field":["Email cannot be blank."],"message":[],"error":true}
如何正确返回JSON中每个字段的所有字段,错误和消息?
由于
答案 0 :(得分:0)
您始终将结果分配给相同的索引,以便只获得最后一条消息 尝试连接消息usinng。=
public function signup() {
if (!$this->validate(array('name')) {
$register_errors['field'] = 'name';
$register_errors['message'] = $this->getErrors('name');
}
if (!$this->validate(array('email')) {
$register_errors['field'] = 'email';
$register_errors['message'] .= $this->getErrors('email');
}
if (!$this->validate(array('password')) {
$register_errors['field'] = 'password';
$register_errors['message'] .= $this->getErrors('password');
}
}
或将不同的讯息分配给不同的$ register_errors [' message'] []
public function signup() {
if (!$this->validate(array('name')) {
$register_errors['field'] = 'name';
$register_errors['message'][] = $this->getErrors('name');
}
if (!$this->validate(array('email')) {
$register_errors['field'] = 'email';
$register_errors['message'][] = $this->getErrors('email');
}
if (!$this->validate(array('password')) {
$register_errors['field'] = 'password';
$register_errors['message'][] = $this->getErrors('password');
}
}
var_dump( $register_errors['message']);