Yii 框架表单验证---实例

 

------------------------------------------------------------------------------------------

表单页面

------------------------------------------------------------------------------------------

第一: 先使用一下类

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\validators\Volidator;
use yii\captcha\Captcha;

第二: Yii 框架自带的各种表单的写法

$form = ActiveForm::begin(['action'=>'index.php?r=form1/index','method'=>'post','options' => ['enctype' => 'multipart/form-data'] ]); ?>
    <?= $form->field($model, 'username',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'okpassword')->passwordInput() ?>
    <?= $form->field($model, 'age') ?>
    <?= $form->field($model, 'sex')->radioList(['男' => '男', '女' => '女']); ?>
    <?= $form->field($model, 'hobby[]')->checkboxList(['游泳' => '游泳', '跑步' => '跑步', '音乐' => '音乐', '学习' => '学习']) ?>

    <?= $form->field($model, 'phone',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'captcha')->widget(Captcha::className(), ['captchaAction'=>'form1/captcha',
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
    <?= $form->field($model, 'email',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'image')->fileInput() ?>
    
    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

----------------------------------------------------------------------------------------------

模型层

----------------------------------------------------------------------------------------------

先使用一下文件上传类  use yii\web\UploadedFile;

    public $captcha;

    /**
     * @验证规则
     */
    public function rules()
    {
        return [
            [['age'], 'integer'],
            [['image'], 'file','skipOnEmpty'=>false, 'extensions'=>'png,jpg,gif'],

            //验证不为空
            ['username', 'required', 'message' => '{attribute}不能为空'],
            ['password', 'required', 'message' => '{attribute}不能为空'],
            ['phone', 'required', 'message' => '{attribute}不能为空'],
            ['email', 'required', 'message' => '{attribute}不能为空'],
            ['age', 'required', 'message' => '{attribute}不能为空'],
            ['sex', 'required', 'message' => '{attribute}不能为空'],
            ['hobby', 'required', 'message' => '{attribute}不能为空'],

            //去掉空格
            ['username', 'filter', 'filter' => 'trim'],
            ['password', 'filter', 'filter' => 'trim'],
            ['okpassword', 'filter', 'filter' => 'trim'],
            ['phone', 'filter', 'filter' => 'trim'],
            ['email', 'filter', 'filter' => 'trim'],
            ['age', 'filter', 'filter' => 'trim'],

            //唯一性验证
            [['phone'], 'unique','message'=>'{attribute}已经被占用'],
            [['username'], 'unique','message'=>'{attribute}已经被占用'],
            [['email'], 'unique','message'=>'{attribute}已经被占用'],

            //正则匹配验证
            [['password'],'match','pattern'=>'/^[a-zA-Z_]\w{6,20}$/','message'=>'{attribute}6-20位数字字母下划线组成,不能以数字开头'],
            [['username'],'match','pattern'=>'/^[a-zA-Z_]\w{6,20}$/','message'=>'{attribute}6-20位数字字母下划线组成,不能以数字开头'],
            [['age'],'match','pattern'=>'/^18|19|([2-4]\d)|50$/','message'=>'{attribute}为18-50以内整数'],
            //['age', 'integer','min'=>18,'max'=>50],
            [['phone'],'match','pattern'=>'/^1[3,5,8]\d{9}$/','message'=>'{attribute}为11位13,15,18开头'],
            ['okpassword', 'required', 'message' => '{attribute}不能为空'],
            ['okpassword','compare','compareAttribute'=>'password','message'=>'{attribute}与{attribute}一致'],
            ['captcha', 'captcha', 'message'=>'请输入正确地{attribute}','captchaAction'=>'form1/captcha'],           
        ];
    }

---------------------------------------------------------------------------------------------

控制器层

---------------------------------------------------------------------------------------------

<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use app\models\Form1;
use yii\web\UploadedFile;

class Form1Controller extends Controller
{
    public function actionIndex()
    {
        $model=new Form1();

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

        if($model->load(Yii::$app->request->post()))
        {
            //var_dump($_POST);die;
            $model->image = UploadedFile::getInstance($model, 'image');
            $model->image->name = time().$model->image->name;
            //print_r($model);die;
            if ($model->validate()){
                $model->image->saveAs('./upload/form1/' . $model->image->baseName . '.' . $model->image->extension);
                //print_r($img);die;
                //获取上传文件的名称   
                $img=$model->image;
                $image=$img->name;
                //print_r($image);die;
                $username=$_POST['Form1']['username'];
                //echo $username;die;
                $password=$_POST['Form1']['password'];
                $okpassword=$_POST['Form1']['okpassword'];
                $age=$_POST['Form1']['age'];
                $phone=$_POST['Form1']['phone'];
                $email=$_POST['Form1']['email'];
                $sex=$_POST['Form1']['sex'];
                //print_r($sex);die;
                $hobby1=$_POST['Form1']['hobby'];
                //print_r($hobby1);die;
                $hobby=implode(',',$hobby1);
                //print_r($hobby);die;
                //添加入库
                $connection = \Yii::$app->db;
                $query = $connection->createCommand()->insert("form1",['username'=>$username,'password'=>$password,'okpassword'=>$okpassword,'age'=>$age,'phone'=>$phone,'email'=>$email,'sex'=>$sex,'hobby'=>$hobby,'image'=>$image]);
                if($query->execute())
                {
                    //echo '成功';
                    // $this->redirect(array('form1/index'));
                    echo "<script>
                        alert('ok');
                        location.href='index.php?r=form1/index';
                    </script>";
                }
                else
                {
                    //echo '失败';
                    echo "<script>
                        alert('no');
                        location.href='index.php?r=form1/index';
                    </script>";
                }
            }
        }
        else
        {
            return $this->render('form',['model'=>$model]);
        }
       
    }
        /**
     * 生成验证码的方法
     */
    public function actions() {
        parent::actions();
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'maxLength' => 3,
                'minLength' => 3
            ],
        ];
    }

}

转载于:https://www.cnblogs.com/bluealine/p/5341047.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值