首页 > 解决方案 > Yii2 $model->save() 和验证码验证规则不起作用

问题描述

尽管有很多关于 Yii2 验证码以及保存问题的问题,但我找不到并回答解决了我的问题。希望有人可以提供帮助:

在我的网站中,我包含了一个联系表格和一个验证码。因此,我向模型、IndexController 和此处描述的表单添加了代码:https ://yii2-cookbook-test.readthedocs.io/forms-captcha/#how-add-captcha-to-a-form 验证 码如果代码输入不正确,则会显示并阻止提交表单。但是,如果我包含验证码验证规则,则消息不会保存到数据库中。所以验证规则似乎有问题。

['verifyCode', 'captcha', 'captchaAction' => '/contact/index/captcha']

我只是不明白这里有什么问题。当我将其注释掉时,模型已保存,但验证码未经过验证。留下带有“captchaAction”的部分会导致 Invalid Captcha ID 错误,解决方案是包含 captchaAction,如下所述:Yii2 Invalid CAPTCHA action ID in module

有谁知道这里可能出了什么问题?围着圈跑...

形式:

...
 <div class="form-group">
     <div><?= Yii::t('ContactModule.form', 'Please enter the letters from the image.'); ?></div>
         <?= $form->field($model, 'verifyCode')->widget(Captcha::class, [
                            'captchaAction' => '/contact/index/captcha',
                       ])->label(false); ?>
 </div> 
...

模型:

class Contact extends ActiveRecord{
    public $verifyCode;

       /**
    * @inheritdoc
    */
   public static function tableName()
   {
       return 'contact';
   }
   /**
    * @inheritdoc
    */
    public function rules()
    {
        return [
            [['name','email','message'], 'required'], //Checking that all the fields are required
            ['email', 'email'], // Validating that email is a valid email
            [['name'],'string', 'max' => 50], //Verifying that name is not greater than its max length
            [['email'], 'string', 'max' => 50], //Verifying that email is not greater than its max length
            [['message'], 'string', 'max' => 255],//Verifying that message is not greater than its max length
            ['state', 'boolean'],
            [['date'], 'date', 'format' => 'php:Y-m-d'],
            ['verifyCode', 'captcha', 'captchaAction' => '/contact/index/captcha'],           
        ];
    }
...

控制器

class IndexController extends Controller
{

    public $subLayout = "@contact/views/layouts/default";

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
            ]
        ];
    }

    /**
     * Renders the index view for the module
     *
     * @return string
     */
    public function actionIndex()
    {
        $model = new Contact();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->save();
...

标签: phpdatabasevalidationyii2captcha

解决方案


推荐阅读