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

表单页面

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

第一: 先使用一下类

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. MySQL – optimizer_search_depth

    Working on customer case today I ran into interesting problem – query joining about 20 tables (thank ...

  2. linux概念之性能调优

    目前,对系统进行性能调试的工具有很多,这些可以两大类:一类是标准的分析工具,即所有的UNIX都会带的分析工具: 另一类是不同厂商的UNIX所特有的性能分析工具,比如HP-UX就有自己的增值性能分析工具 ...

  3. BNUOJ 1006 Primary Arithmetic

    Primary Arithmetic 来源:BNUOJ 1006http://www.bnuoj.com/v3/problem_show.php?pid=1006 当你在小学学习算数的时候,老师会教你 ...

  4. html之label标签

    label标签为input元素定义标注,label标签与相关元素通过id属性绑定在一起. 相关属性: for:规定label绑定到哪个表单元素 form:规定label字段所属的一个或多个表单 示例代 ...

  5. 【Reporting Services 报表开发】— 级联式参数设置

    级联式参数设置 再清楚的菜单,只要遇到选择项目一多的时候,难免会让人眼花缭乱,而找不到该选的选项.举例来说,像是零售业动辄万种商品品类,如果希望快速的选择到希望查看的产品品类时,就需要更有效率的搜索方 ...

  6. Spark(二): 内存管理

    Spark 作为一个以擅长内存计算为优势的计算引擎,内存管理方案是其非常重要的模块: Spark的内存可以大体归为两类:execution和storage,前者包括shuffles.joins.sor ...

  7. 【linux】ps 命令详解

    [root@andon lib]# ps aux ###常用格式 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0 ...

  8. android学习笔记七——控件(DatePicker、TimePicker、ProgressBar)

    DatePicker.TimePicker ==> DatePicker,用于选择日期 TimePicker,用于选择时间 两者均派生与FrameLayout,两者在FrameLayout的基础 ...

  9. python安装psycopg2

    vim ~/.bash_profile export PATH=/Applications/Postgres.app/Contents/Versions/9.4/bin/:$PATH pip inst ...

  10. 设计模式的一些杂谈与反思---functionn和signals

    以下关于GOF的一些例子命名不是很准确,但是大概意思差不多,懒得再去翻书了 模拟观察者模式 模拟中介者模式 模拟command模式 模拟memento和command   模拟观察者模式 观察者与职责 ...