dongxin1999 2015-04-09 10:28
浏览 158

Yii2 ajax验证不起作用

I was trying to validate my YII2 register form but it not work. In view:

$form = ActiveForm::begin([
    'id'                   => 'register',
    'options'              => ['accept-charset'=>'utf-8'],
    'validateOnChange'     => false,
    'enableAjaxValidation' => true,
    'validateOnSubmit'     => true,
])

In controller:

$model = new MUser();

if($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax)
{
    $model->refresh();
    Yii::$app->response->format = 'json';
    return ActiveForm::validate($model);
}
elseif($model->load(Yii::$app->request->post()) && $model->save())
{
    \\do something
}

In Model:

public function rules()
{
    return [
               [
                   'username', 
                   'unique', 
                   'targetClass' => 'com\modules\admin\models\MUser',
                   'message'     => 'Username exist',
               ]
           ];
}

Can anyone let me know what wrong I am doing?

  • 写回答

1条回答 默认 最新

  • duanqianhuan3994 2015-12-02 11:55
    关注

    change

    return ActiveForm::validate($model)
    

    TO

     echo json_encode(ActiveForm::validate($model));
            \Yii::$app->end();
    

    ActiveForm::validate($model) is an array it needs to be represented in json form which is done by json_encode and \Yii::$app->end(); is making sure that the application stop on just checking.Also make sure you have after the namespace :

    use yii\web\Response;
    use yii\widgets\ActiveForm;
    

    But By doing so the submission via ajax of your form will not work the perfect way is using validationUrl.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号