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

表单页面

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

第一: 先使用一下类

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
            ],
        ];
    }

}

Yii 框架表单验证---实例的更多相关文章

  1. jQuery-easyui和validate表单验证实例

    jQuery EasyUI 表单 - 表单验证插件validatebox 使用时需要向页面引入两个css文件如下: <link rel="stylesheet" href=& ...

  2. Bootstrap+PHP表单验证实例

    简单实用的Bootstrap+PHP表单验证实例,非常适合初学者及js不熟悉者,还有ajax远程验证 js验证表单 1 $(document).ready(function() { 2 $('#def ...

  3. jquery-4 完整表单验证实例

    jquery-4 完整表单验证实例 一.总结 一句话总结:在form的jquery对象中返回false即可终止表单提交. 1.验证的显示错误消息如何布局? 开始时隐藏,出现错误后显示 10 .erro ...

  4. HTML5 web Form表单验证实例

    HTML5 web Form 的开发实例! index.html <!DOCTYPE html> <html> <head> <meta charset=&q ...

  5. tp框架表单验证

    之前的表单验证都是用js写的,这里也可以使用tp框架的验证.但是两者比较而言还是js验证比较好,因为tp框架验证会运行后台代码,这样运行速度和效率就会下降. 自动验证是ThinkPHP模型层提供的一种 ...

  6. php--yii框架表单验证

    在视图层利用表单小部件生成表单时,field只能是数据库中存在的, 例如: use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\capt ...

  7. tp框架表单验证 及ajax

    之前的表单验证都是用js写的,这里也可以使用tp框架的验证.但是两者比较而言还是js验证比较好,因为tp框架验证会运行后台代码,这样运行速度和效率就会下降. 自动验证是ThinkPHP模型层提供的一种 ...

  8. ThinkPHP框架表单验证

    对注册到test表的表单进行验证 在注册之前要对表单进行验证: 用户名非空验证,两次输入密码必须一致即相等验证,年龄在18~50之间即范围验证,邮箱格式正则验证. 自动验证是ThinkPHP模型层提供 ...

  9. angular表单验证实例----可用的代码

    前段时间,公司做一个单页面,就是一个表单验证,早开始在菜鸟教程上关注了angular,所以下派上用场了 angular里面对于表单验证,设置了很多指令. 也就是说不用自己写一些逻辑,直接绑定指令就行. ...

随机推荐

  1. Java 性能优化

    http://eclipsesource.com/blogs/2013/01/21/10-tips-for-using-the-eclipse-memory-analyzer/ http://docs ...

  2. share point 读取 List数据

    SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite oSite = new SPSite(siteUrl)) { forea ...

  3. linq字符串搜索条件,排序条件-linq动态查询语句 Dynamic LINQ

    在做搜索和排序的时候,往往是前台传过来的字符串做条件,参数的数量还不定,这就需要用拼sql语句一样拼linq语句.而linq语句又是强类型的,不能用字符串拼出来. 现在好了,有个开源的linq扩展方法 ...

  4. unity, particleSystem的batch优化

    一,单个光效的batch优化 理想状态下一个由若干粒子堆出来的光效只需要一至两个draw call: (1)至多使用alpha blend(垫底色)和additive(曝光)两个材质球,两shader ...

  5. unity, GL.TexCoord or GL.Color must put before GL.Vertex!!!

    GL.Begin(GL.QUADS);                //in unity, should use left hand rule        //RU        GL.TexCo ...

  6. HOCON 了解

    Spec This is an informal spec, but hopefully it's clear. Goals / Background The primary goal is: kee ...

  7. WCF Client is Open Source

    WCF Client is Open Source Wednesday, May 20, 2015 Announcement New Project WCF We’re excited to anno ...

  8. selenium+python自动化之操作浏览器

    一.打开网站 1.第一步:从selenium里面导入webdriver模块 2.打开Firefox浏览器(Ie和Chrome对应下面的) 3.打开百度网址 二.设置休眠 1.由于打开百度网址后,页面加 ...

  9. sqlserver修改某列为行号

    UPDATE t_users  SET t_users.id=u.num1 FROM t_users INNER JOIN (SELECT row_number() over(order by id) ...

  10. 服饰行业淘宝商城店铺首页设计报告-转载自http://bbs.paidai.com/topic/88363

    店铺的设计 和 美工是2个完全不同的工作. 很多中小卖家,往往会模糊他们之间的差别. 好比要建造一座金茂大厦,先要有建筑设计师设计图纸,明确好建造的楼层数,具体框架结构,所用材料等等. 然后建筑施工队 ...