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

表单页面

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

第一: 先使用一下类

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. 数据库事务隔离级ORACLE数据库事务隔离级别介绍

    本文系转载,原文地址:http://singo107.iteye.com/blog/1175084 数据库事务的隔离级别有4个,由低到高依次为Read uncommitted.Read committ ...

  2. C#中IP地址转换为数值的方法

    任何语言都通用的方法转换 IP 地址 a.b.c.d ==> a***+b**+c*+d ===> *(c+*(b+*a)) +d 示例: ***+**+*+ ===> *( +*( ...

  3. php开发memcached

    一.memcached 简介 memcached是高性能的分布式内存缓存服务器.一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度.提高可扩展 性.它可以应对任意 ...

  4. ABBYY FineReader出现错误和警告提示的解决办法

    识别结果的质量取决于多种因素,这些因素包括原始文档的质量.结构布局和文档导出参数等.在使用ABBYY FineReader Pro for Mac OCR文字识别软件处理文档的各个阶段,应用程序均可能 ...

  5. 64位python安装MySQL-python 1.2.5

    在64位的python直接安装MySQL-python 1.2.5有问题,参考http://www.linuxfly.org/windows_install_mysql_python_library/ ...

  6. webpack需要全局安装,才能使用webpack命令

    webpack全局安装,具体项目中才能使用webpack命令: npm install webpack -g

  7. mysql.server 文件修改起动多实例

    如果你用mysql.server来启动的话,就要注意一下点,要修改一下里面的内容,修改如下:大约218行左右 查看复制打印? then print_defaults="$bindir/mys ...

  8. 用php自带的filter函数验证、过滤数据 -转载

    PHP过滤器包含两种类型 Validation:用来验证验证项是否合法 Sanitization:用来格式化被验证的项目,因此它可能会修改验证项的值,将不合法的字符删除等. input_filters ...

  9. ORA-27086: unable to lock file - already in use

    问题现象: SQL> startup ORACLE instance started. Total System Global Area 1854021632 bytes Fixed Size  ...

  10. windows下脚本配置IP地址

    带着笔记本有时候在固定的地方工作,需要用到同一个的Ip地址.换个地方换个Ip,又要重新输一遍. 开始感觉这个过程很繁琐,因为是window工作环境,一开始想到了vbs脚本. 无意中发现了强大的nets ...