您的位置:首页 > 编程语言 > PHP开发

请教下 Yii 和 Ajax来验证用户名是否存在

2013-12-17 11:21 369 查看
添加一个 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验证的用户名,

ajax验证是在输入完成后,失去焦点的时候验证.

'validateOnSubmit'=>true你点击提交按钮的时候,是前端验证。

<?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));
}


在控制器中,输入完用户名后,执行了

echo CActiveForm::validate($model);

这句话,但是数据库中已经有该NAME存在的时候,前台页面 CustomView 并没有显示错误信息,也就是 在model里面设置的

array('name','unique','message'=>'用户名'.$this->name.'已存在'),

message 中的 信息, 但点击提交的时候是被拦截阻止了的,因为数据库中已经存在。

页面上通过<?php echo $form->error($model,'name');?>显示错误信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: