天天看點

thinkphp自動驗證方法的使用

建一個表單:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="{:U('Index/check')}" method='post'>
        <table>
            <tr>
                <td>使用者名:</td><td><input type="text" name='name'></td>
            </tr>
            <tr>
                <td>密碼:</td><td><input type="password" name='password'></td>
            </tr>
            <tr>
                <td>性别:</td><td><input type="radio" name='sex' vlue='1'>男<input type="radio" name='sex' value='0'>女</td>
            </tr>
            <tr>
                <td>年齡:</td><td><input type="text" name='age'></td>
            </tr>
            <tr>
                <td>郵箱:</td><td><input type="text" name='email'></td>
            </tr>
            <tr>
                <td>個人網頁:</td><td><input type="text" name='mypage'></td>
            </tr>
            <tr>
                <td>薪水:</td><td><input type="text" name='salary'></td>
            </tr>
        </table>
        <input type="submit" value='儲存添加'>
    </form>
</body>
</html>      

建一個模型,UserModel.php

<?php 
namespace Home\Model;
use Think\Model;

class UserModel extends Model{
    protected $_validate = array(
     array('name','require','帳号不能為空!'), 
     array('password','require','密碼不能為空'), 
  );
}
 ?>      

在控制器中調用方法

<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $this->display();
        }
    public function check(){

         $user = D('User'); // 執行個體化User對象
   
        if (!$user->create()){
             // 如果建立失敗 表示驗證沒有通過 輸出錯誤提示資訊
             exit($user->getError());
        }else{
             // 驗證通過 可以進行其他資料操作 
            echo 1;
            }
    }
}      

轉載于:https://www.cnblogs.com/hltswd/p/5096849.html

php