控制器层

<?php

namespace frontend\controllers;

use Yii;
use frontend\models\FormsModel;
use yii\web\UploadedFile; class FormsController extends \yii\web\Controller
{
/**
* 生成验证码的方法
*/
public function actions() {
parent::actions();
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
//'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//'backColor'=>0x00ff00,//背景颜色
//'padding'=>5,//间距
//'height'=>40,//高度
//'width'=>150,//宽度
//'foreColor'=>0x000000,//字体颜色
//'offset'=>4,//设置字符偏移量 有效果
'maxLength' => 3,
'minLength' => 3
],
];
} public function actionIndex()
{
$model = new FormsModel;
if($model->load(Yii::$app->request->post())){
//ajax验证唯一性
if (Yii::$app->request->isAjax)
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return \yii\bootstrap\ActiveForm::validate($model, ['username', 'email', 'phone']);
}
//上传图片
$model->userimg= UploadedFile::getInstance($model, 'userimg');
if($files = $model->upload()){
$post = Yii::$app->request->post();
//var_dump($post);die;
$hobbys = $post['FormsModel']['hobby'];
$model->hobby = implode(',',$hobbys);
$model->userimg = $files;
if($model->save(false)){
echo 'ok';
} else {
echo '添加失败';
}
} else {
//上传失败
print_r($model->errors);
}
} else {
return $this->render('index',['model'=>$model]);
} } } 验证模型层
<?php namespace frontend\models; use Yii;
use yii\captcha\Captcha; /**
* This is the model class for table "forms".
*
* @property integer $id
* @property string $username
* @property string $password
* @property integer $age
* @property string $sex
* @property string $phone
* @property string $email
* @property string $userimg
* @property string $hobby
*/
class FormsModel extends \yii\db\ActiveRecord
{
public $captcha;
public $repassword;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'forms';
} /**
* @inheritdoc
*/
public function rules()
{
return [ [['username', 'password', 'repassword', 'workyear', 'age', 'sex', 'phone','email','hobby','selfdesc'], 'required', 'message'=>'{attribute}不能为空'],
[['username', 'password', 'repassword', 'workyear', 'age', 'sex', 'phone','email','selfdesc'], 'filter', 'filter'=>'trim'],
[['username'], 'match', 'pattern'=>'/^\w{6,20}$/', 'message'=>'{attribute}为6-20位数字字母或下划线'],
//['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['password','match','pattern'=>'/^[a-zA-z]\w{5,20}$/','message'=>"{attribute}6-20位数字字母下划线组成,不能以数字开头"],
['repassword','compare','compareAttribute'=>'password','message'=>"两次密码不一致"],
['age','number','integerOnly'=>true,'max'=>50,'min'=>18,"tooBig"=>"18-50以内的整数","tooSmall"=>'18-50以内的整数'], ['sex', 'in', 'range'=>['男', '女'], 'message'=>'{attribute}只能是男或女'],
['phone', 'match', 'pattern'=>'/^1[3,5,8]\d{9}$/','message'=>"{attribute}必须由13,15,18开头且11位数字组成"],
['selfdesc','match','pattern'=>'/^[\x{4e00}-\x{9fa5}]{3,18}$/u','message'=>"{attribute}必须由3到18个汉字组成"],
[['username','email','phone'],'unique','message'=>"{attribute}必须唯一"], //['phone', 'checkPhone'],
['email', 'email'],
//['email', 'unique'],
['userimg', 'file', 'skipOnEmpty'=>false, 'extensions'=>'png,jpg,gif'],
['captcha', 'captcha', 'message'=>'请输入正确地{attribute}','captchaAction'=>'forms/captcha'], ];
} /**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => '用户名',
'password' => '密码',
'age' => '年龄',
'sex' => '性别',
'phone' => '电话',
'email' => '邮箱',
'userimg' => '图片',
'hobby' => '爱好',
'repassword'=>'确认密码',
'captcha'=>'验证码',
'workyear'=>'工作经验',
'selfdesc'=>'自我描述',
];
}
//上传图片
public function upload()
{
if ($this->validate()) {
$this->userimg->saveAs('./upload/forms/' . $this->userimg->baseName . '.' . $this->userimg->extension);
return $this->userimg->baseName . '.' . $this->userimg->extension;
} else {
return false;
}
}
}
工作经验模型层 <?php namespace frontend\models; use Yii; /**
* This is the model class for table "workyear".
*
* @property integer $w_id
* @property integer $workyear
*/
class WorkyearModel extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'workyear';
} /**
* @inheritdoc
*/
public function rules()
{
return [
[['workyear'], 'string', 'max' => 50]
];
} /**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'w_id' => 'W ID',
'workyear' => '工作经验',
];
}
} 视图层 <?php use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
use frontend\models\WorkyearModel; /* @var $this yii\web\View */
/* @var $model frontend\models\FormsModel */
/* @var $form ActiveForm */
?>
<div class="forms-index"> <?php $form = ActiveForm::begin(['id'=>'sign-form', 'options'=>['action'=>'forms/index', 'method'=>'post', 'enctype'=>'multipart/form-data']]); ?> <?= $form->field($model, 'username',['enableAjaxValidation' => true])->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'repassword')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'sex')->radioList(['男'=>'男','女'=>'女']) ?>
<?= $form->field($model, 'age')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'phone',['enableAjaxValidation' => true])->textInput(['maxlength' => true]) ?>
<?= $form->field($model,'workyear')->dropdownList(WorkyearModel::find()->select(['workyear', 'w_id'])->
      indexBy('w_id')->column(),['prompt'=>'请选择工作经验']);?>
<?= $form->field($model, 'email',['enableAjaxValidation' => true]) ?>
<?= $form->field($model, 'hobby')->checkboxList(['唱歌'=>'唱歌','跳舞'=>'跳舞','看电影'=>'看电影']) ?>
<?= $form->field($model, 'selfdesc')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'userimg')->fileInput() ?>
<?= $form->field($model, 'captcha')->widget(Captcha::className(), ['captchaAction'=>'forms/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?> <div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div> <?php ActiveForm::end(); ?> </div><!-- forms-index --> 解析:
Filter: 过滤,'filter'=>'trim',表示去空格
Required:必须的,表示不能为空
Match: 匹配正则,需要和pattern一起使用,定义正则表达式,'pattern'=>'/^\w{6,20}$/',
Unique:验证数据唯一性,在注册时用到的比较多,这里需要注意的是,在rules规则里面定义的唯一性验证,只有在服务器端才能验证,
如果想要在表单页面显示,需要开启”enableAjaxValidation”=>ture;
例如:
<?php $form = ActiveForm::begin([
'id'=>'sign-form',
//'enableAjaxValidation' => true,//启用ajax验证,将属性值发送到服务器端进行验证并返回结果,默认为false
'enableClientValidation' => true,//启用客户端验证,默认值为true,关闭后表单无js验证
'options'=>['action'=>'usermessage/signform', 'method'=>'post', 'enctype'=>'multipart/form-data']]); ?>
这里需要注意的是,在这里启用的话,ajax验证是作用于所有的属性的,所以,还有另一种开启方式,在某一个field里面开启:
<?= $form->field($model, 'username', ['enableAjaxValidation'=>true])->textInput() ?>,这样就单独作用于username属性了。
要想实现表单ajax验证唯一性,后台还要一个ajax判断:
$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);
}
在有数据提交时,最好先执行$model->load(Yii::$app->request->post()); 操作,不要做多余的处理,然后判断ajax,否则ajax验证的时候可能会报错500。如果有验证码,
这里就会有另一个问题:return \yii\bootstrap\ActiveForm::validate($model);这个验证的是所有的属性,而验证码执行validate后就会重新生成,
那么在表单提交时我们进行数据有效性验证时就会报错,
解决方式:\yii\bootstrap\ActiveForm::validate()这个方法其实是有两个参数的,$model,$attributes,我们可以指定ajax验证某一些特定的属性,
写法是:\yii\bootstrap\ActiveForm::validate($model, ['username', 'email', 'phone']);
这样ajax验证时就只验证username,email,phone这三个字段了,不会影响验证码。 Number:数字验证,加上'integerOnly'=>true,表示只能是整数,max,min分别表示最大最小值,tooBig和tooSmall分别是超过最大值和低于最小值时的错误提示信息
Compare:比较,用于两个属性之间的比较,'compareAttribute'=>'password',表示与password比较
In:和range连用,定义范围,表示属性值必须在这个范围内,通常用于验证某些固定值
Email:邮箱验证
File:文件验证 extensions可以定义上传文件的类型
Captcha:验证码验证,需要定义生成验证码的方法,'captchaAction'=>'usermessage/captcha',usermessage表示控制器名,captcha表示方法名
可以在控制器层定义一个actions方法添加captcha方法:
/**
* 生成验证码的方法
*/
public function actions() {
parent::actions();
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
//'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'maxLength' => 3,
'minLength' => 3
],
];
} 每一个验证都可以添加应用场景:’on’=>’register’;
在控制器层实例化模型层
$model = new Usermessage();
$model->setScenario('register'); 定义使用应用场景为register
在模型层需要定义场景作用的对象 /**
* 定义验证场景
*/ public function scenarios()
{
return [
'register' => ['username', 'password', 'repassword', 'age', 'sex', 'phone','email'],
'login' => ['username', 'password','age', 'sex', 'phone','email'],
];
} 然后在对应的验证规则后面限定应用场景’on’=>’register’;
当表单验证时,为在作用场景以内的参数可以不受验证规则的限制 添加入库:复选框因提交过来后是一个数组,所以在执行save()前需要将复选框的值处理成字符串

yii2 数据验证的更多相关文章

  1. yii2之数据验证

    一.场景 什么情况下需要使用场景呢?当一个模型需要在不同情境中使用时,若不同情境下需要的数据表字段和数据验证规则有所 不同,则需要定义多个场景来区分不同使用情境.例如,用户注册的时候需要填写email ...

  2. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

  3. MVC 数据验证

    MVC 数据验证 前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解.System.ComponentModel.DataAnnotations 一.基础特性 一.Required 必填 ...

  4. kpvalidate开辟验证组件,通用Java Web请求服务器端数据验证组件

    小菜利用工作之余编写了一款Java小插件,主要是用来验证Web请求的数据,是在服务器端进行验证,不是简单的浏览器端验证. 小菜编写的仅仅是一款非常初级的组件而已,但小菜为它写了详细的说明文档. 简单介 ...

  5. MVC3 数据验证用法之密码验证设计思路

    描述:MVC数据验证使用小结 内容:display,Required,stringLength,Remote,compare,RegularExpression 本人最近在公司用mvc做了一个修改密码 ...

  6. jQuery MiniUI开发系列之:数据验证

    在开发应用系统界面时,往往需要进行很多.复杂的数据验证,当填写的数据符合规定,才能提交保存. jQuery MiniUI提供了比较完美的表单数据验证和错误显示的方式. 常见的表单控件,都有一个验证事件 ...

  7. AngularJS快速入门指南14:数据验证

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  8. atitit.数据验证--db数据库数据验证约束

    atitit.数据验证--db数据库数据验证约束 1. 为了加强账户数据金额的安全性,需要增加验证字段..1 2. 创建帐户1 3. 更改账户2 4. ---code3 5. --fini4 1. 为 ...

  9. MVC数据验证原理及自定义ModelValidatorProvider实现无编译修改验证规则和错误信息

    Asp.net MVC中的提供非常简单易用的数据验证解决方案. 通过System.ComponentModel.DataAnnotations提供的很多的验证规则(Required, StringLe ...

随机推荐

  1. 联系 管理 Hibernate4+Spring JPA+SpringMVC+Volecity搭建web应用(三)

    hibernate注解实体类示例 package cn.bdqn.smvc.entity; import java.io.Serializable; import javax.persistence. ...

  2. poj------(3468)A Simple Problem with Integers(区间更新)

    A Simple Problem with Integers Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 60745   ...

  3. Objective-C:Foundation框架-常用类-NSDictionary

    与NSString.NSArray一样,NSDictionary是不可变的,其对应可变类型为NSMutableDictionary.其用法如下: #import <Foundation/Foun ...

  4. 【转】Session ID/session token 及和cookie区别

    Session + Cookie  知识收集! cookie机制采用的是在客户端保持状态的方案.它是在用户端的会话状态的存贮机制,他需要用户打开客户端的cookie支持.cookie的作用就是为了解决 ...

  5. Configure,make,make install详解

    转:http://my.oschina.net/qihh/blog/66113?fromerr=6ej3CfGJ   无论对于一个初学者还是一个资深的Linux程序员,编写Makefile文件都是一件 ...

  6. 碰到sshd连接不上linux时的解决办法

    1,首先更改ssh配置,可以是ssh端口连接不上服务器 cd /etc/ssh/sshd_config vi !$ Port 52113 //ssh默认的连接端口, 改为别人不知道的端口 Permit ...

  7. GUID

    前言 全局唯一标识符,简称GUID(发音为 /ˈɡuːɪd/或/ˈɡwɪd/),是一种由算法生成的唯一标识,通常表示成32个16进制数字(0-9,A-F)组成的字符串,如:{21EC2020-3AEA ...

  8. Windows内核对象

    1. 内核对象 Windows中每个内核对象都只是一个内存块,它由操作系统内核分配,并只能由操作系统内核进行访问,应用程序不能在内存中定位这些数据结构并直接更改其内容.这个内存块是一个数据结构,其成员 ...

  9. 53个要点提高PHP编程效率

    1.如果能将类的方法定义成static,就尽量定义成static,它的速度会提升将近4倍. 2.$row[’id’] 的速度是$row[id]的7倍.3.echo 比 print 快,并且使用echo ...

  10. bzoj 2730: [HNOI2012]矿场搭建

    #include<cstdio> #include<cstring> #include<iostream> #define M 508 using namespac ...