好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

thinkphp之3.1版本自动验证 - Thinkphp

thinkphp之3.1版本自动验证

新版本出来之后,也可以在 controller里面验证,需要指定两个变量一个是 $validate $auto 里面指定的规则和 model中一样。

之前用把自动验证放在model里面总是有问题,先D实例化model类。

注意: 只有先 $user->auto($auto)->validate($validate)->create()生成对象,这样才支持自动验证.

然后date数组要保留,因为像我做的这个注册,如果不用date单独从post数组中抽出来。

user->add();是不成功的,他默认是post的数据,有了date数组,应该添加的是date数组,放在controller里面一切正常上代码:

  $user =D( 'User' );  $data [ 'username' ]= $_POST [ 'username' ];  $data [ 'password' ]= $_POST [ 'password' ];  $data [ 'email' ]= $_POST [ 'email' ];  $validate = array (  array ( 'username' , 'require' , '用户名不能为空' ,1),  array ( 'username' , '' , '用户名已经存在' ,1, 'unique' ,1),  array ( 'confirm_password' , 'password' , '确认密码不正确' ,0, 'confirm' ),  );  $auto = array (  array ( 'password' , 'md5' ,1, 'function' ),  array ( 'reg_time' , 'time' ,1, 'function' ),  );  if ( $user ->auto( $auto )->validate( $validate )->create())  {    $user ->add();  echo   $user ->getLastSql(); exit ;  }  else   {  $this ->error( $user ->getError());  } 

ajax验证, thinkphp中$.post方式验证用户名存在还是不存在,实例代码如下:

$.post('__URL__/checks',{'username':s,'aa':'bb'},function(data){

alert(data.data.info);

});

php代码如下:

$user =D( 'User' );     if ( $user ->getByUsername( $_POST [ 'username' ]))  {  //info           //$this->success('已经存在用户名','1111');           $this ->ajaxReturn( array ( 'info' => 'cunzai' , 'sss' => 'dddd' ), "已经存在!" ,1);           //这里用 success方法和 ajaxReturn有很大的区别。 ajaxReturn里面可以返回自定义设置。success方式固定返回的参数      }    else     {     $this ->error( '不存在用户名' );     } 

查看更多关于thinkphp之3.1版本自动验证 - Thinkphp的详细内容...

  阅读:84次