控制器层

<?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. Pictures of Ascii Art

    简述 指尖上的艺术 - 通过键盘上韵律般的敲敲打打,一幅幅美轮美奂的艺术作品便跃然于屏. 这样的画作,包含了无穷的创意,糅合了现代计算机科技与传统绘画艺术,难道还有比这更令人陶醉的美妙事物吗? 简述 ...

  2. jQuery 2.0.3 源码分析 bind/live/delegate/on

    传统的时间处理: 给某一个元素绑定一个点击事件,传入一个回调句柄处理 element.addEventListener('click',doSomething,false); 这样的绑定如果页面上面有 ...

  3. Laravel

    Laravel是一套简洁.优雅的PHP Web开发框架(PHP Web Framework).它可以让你从面条一样杂乱的代码中解脱出来:它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁.富于 ...

  4. JDE变量说明

    BC Business view columns. Columns that are included in the attached business view. These columns are ...

  5. 源码编译Chrome

    官网描述 http://www.chromium.org/developers/how-tos/build-instructions-windows 为啥还要写这篇博客 太久没在这里写博客 Chrom ...

  6. JS解析json数据并将json字符串转化为数组的实现方法

    json数据在ajax实现异步交互时起到了很重要的作用,他可以返回请求的数据,然后利用客户端的js进行解析,这一点体现出js的强大,本文介绍JS解析json数据并将json字符串转化为数组的实现方法, ...

  7. Android第三方开源对话消息提示框:SweetAlertDialog(sweet-alert-dialog)

    Android第三方开源对话消息提示框:SweetAlertDialog(sweet-alert-dialog) Android第三方开源对话消息提示框:SweetAlertDialog(sweet- ...

  8. Oracle合并函数内容

    --MINUS去差集,取第一个集合有的而第二集合没有的,并以第一个字段排序select t.bumenbm from T_HQ_BM t minus select b.bumenbm from t_h ...

  9. POJ 1125 Stockbroker Grapevine 最短路 难度:0

    http://poj.org/problem?id=1125 #include <iostream> #include <cstring> using namespace st ...

  10. Zabbix源码包安装

    Zabbix源码包安装 Cenos5.3 Basic server 安装顺序 Libxml2 Libmcrypt Zlib Libpng Jpeg:需要创建目录jpeg  /bin  /lib   / ...