请教下 Yii 和 Ajax来验证用户名是否存在 [ 未指定版本 ]
添加一个 Custom,
Model页面: CustomForm中:
public function rules()
{
// 使用ajax 校验数据
return array(
array('name','required','message'=>'用户名不能为空'),
array('name','unique','message'=>'用户名'.$this->name.'已存在'),
array('email','required','message'=>'邮箱不能为空'),
// Email的验证使用 extension中的验证方法进行.
array('email','ext.MyValidators.EmailsValidators'),
// Email也必须是唯一的;
array('email','unique','message'=>'电子邮箱'.$this->email.'已经被注册,请更换'),
);
} 在View页面,AddCustom.php中,只罗列了需要Ajax验证的用户名,
<?php
$form = $this -> beginWidget('CActiveForm',
array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'action'=>array('Custom/Add'),
'htmlOptions'=>array(
'name'=>'AddCustom',
'enctype'=>'multipart/form-data'
),
'clientOptions'=>array('validateOnSubmit'=>true),
)
);
?>
<table border="0" cellpadding="2" cellspacing="1" style="width:100%">
<tr>
<td width="14%" height="40" align="right" valign="middle" nowrap><?php echo $form->label ( $CustomModel ,'name');?></td>
<td width="25%" align="left" valign="middle" class="text"><?php echo $form -> textField( $CustomModel, 'name');?>
<span class="red">*</span></td>
<td width="25%" align="left" valign="middle" nowrap class="font201"><?php echo $form->error($CustomModel,'name');?> </td>
<td width="36%" align="left" valign="middle"> </td>
</tr>
<TD colspan="2" align="center" height="50px">
<?php echo CHtml::submitButton('submit',array('class'=>'button','name'=>'sub','value'=>'submit')); ?>
<?php echo CHtml::resetButton('reset',array('class'=>'button','name'=>'ret','value'=>'reset'));?></TD>
</TR>
<?php
$this -> endWidget();
?>
在控制器:CustomController.php中
/**
* 渲染 Custom添加页面
*
* 并接受CustomForm提交
* 请求的处理
*/
public function actionAdd()
{
$model = new CustomForm;
// ajax validate.
if( isset($_POST['ajax']) && $_POST['ajax'] === 'user-form')
{
echo CActiveForm::validate($model);
Yii::app() -> end();
}
// submit handle and vaildate.
if( isset($_POST['CustomForm']))
{
foreach( $_POST['CustomForm'] as $k => $v)
{
$model -> $k = $v;
}
if($model->validate() && $model->save())
{
$this -> redirect('./index.php?r=Custom/Succeed');
}
else
{
$this -> redirect('./index.php?r=Custom/Failed');
}
}
$this -> render('AddCustom',array('CustomModel'=>$model));
}
</pre><br /><p></p><p></p><pre class="prettyprint lang-html"> 在控制器中,输入完用户名后,执行了 <pre class="prettyprint lang-html"><pre class="prettyprint lang-php"><pre class="prettyprint lang-php">echo CActiveForm::validate($model);</pre> 这句话,但是数据库中已经有该NAME存在的时候,前台页面 CustomView 并没有显示错误信息,也就是 在model里面设置的<br /> <pre class="prettyprint lang-php"> array('name','unique','message'=>'用户名'.$this->name.'已存在'),</pre><br /></pre></pre> message 中的 信息, 但点击提交的时候是被拦截阻止了的,因为数据库中已经存在。<br /><br />请问怎么才能让提示信息显示出来。<br /> <br /></pre><br /><p></p>
共 3 个回答
-
icultivator 回答于 2013-11-18 09:01 举报你是要显示message中的$this->name吗,那样的话应该用'message'=>'用户名{value}已存在'来显示
-
-
麦蔸
注册时间:2013-11-07
最后登录:2013-11-18
在线时长:2小时20分
最后登录:2013-11-18
在线时长:2小时20分
- 粉丝0
- 金钱0
- 威望0
- 积分20