Yii2 ActiveForm唯一验证未显示错误消息

时间:2015-12-16 07:13:55

标签: yii2

这是我的模特联系人,

public function rules()
{
    return [
        [['fname', 'status','mobile',], 'required'],
        [['user_id', 'contact_type','group_type','passport_no','trip_id','group_id','state',], 'integer'],
        [['fname', 'mname', 'lname', 'status', 'street', 'location', 'post', 'city', 'district','email','job_title','company_name','source'], 'string', 'max' => 500],
        [['department'], 'string', 'max' => 40],
        [['pincode'], 'string', 'max' => 15],
        [['mobile'],'unique'],

此处mobile所需的验证工作并显示错误消息,但唯一规则有效,但未显示任何错误消息

帮帮我。

5 个答案:

答案 0 :(得分:2)

1)数据库的唯一验证工作 2)提交表单后,检查验证,由于唯一验证失败,模型未保存 3)如果您想在表单上进行唯一验证,请使用Ajax。

为此,您需要设置'enableAjaxValidation' => true

$form = ActiveForm::begin([
    'id' => 'contact-form',
     'enableAjaxValidation' => true,
]);

控制器:

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) 
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}

Reference

答案 1 :(得分:1)

也许您还应该设置targetClass

['email', 'unique', 'targetClass' => '\common\models\User']

答案 2 :(得分:1)

我假设您的观看页面为register.php。所以,

register.php (查看)

1)删除use yii\bootstrap\ActiveForm;(如果存在)

2)添加use yii\widgets\ActiveForm;

3)在该字段中添加'enableAjaxValidation' => true(您要验证的位置。如下所示)

<?= $form->field($model, 'mobile',['enableAjaxValidation' => true])->textInput(['class'=>'form-control']) ?>

<强>控制器

见下文(在我写的任何地方添加此行//Add This Line

.
.
use yii\web\Response; // Add This line
use yii\widgets\ActiveForm; //Add This Line
.
.
Class SomeClass 
{
    .
    .
    .   

    public function actionRegister() {

     $model = new Candidate();

     //Add This For Ajax Mobile Exist Validation 
     if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
       Yii::$app->response->format = Response::FORMAT_JSON;
       return ActiveForm::validate($model);
     } 

     else if ($model->load(Yii::$app->request->post())) {
        .
        // Your code
        .
        .
     }
  }
}

<强>模型

[['mobile'],'unique','message'=>'Mobile No Already Exist'],

供参考 - 点击Validate unique value from database in Yii2

答案 3 :(得分:1)

if ($model->validate()) {
    //SAVE YOUR DATA
} else {
    // HERE YOU CAN PRINT THE ERRORS OF MODEL
    $data = $model->getErrors();
    Yii::$app->session->setFlash('message', $data['password'][0]);// its dislplays error msg on your form
}

答案 4 :(得分:0)

我的模型中的这个规则对我有用:

['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\app\models\Student', 'message' => 'This email address has already been taken.'],