PHP应用程序中的表单验证

时间:2017-04-09 16:25:30

标签: php forms validation model-view-controller

最近我在PHP中构建Web应用程序。为了学习,我从头开始构建它(不使用框架)。

我有关于表单验证的问题(注册和登录表格具体)。

使用jQuery验证表单字段是否可以(例如检查所有字段是否已满,检查电子邮件是否写得正确,......)然后,如果一切正常,请将表单提交给我的控制器?

class RegistrationController extends Controller {

    public function __construct($data = array()) {
        userService = new UserService();
        parent::__construct($data);
    }

    public function index() {
        // form fields are correctly filled in

        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $firstName = $_POST['reg-form-first-name'];
            $lastName = $_POST['reg-form-last-name'];
            $email = $_POST['reg-form-email'];
            $password = $_POST['reg-form-password'];

            userService->createNewUser($firstName,...);
        }
    }
}

或者我应该在PHP模型中验证表单?如果这是正确的方法,请解释我应该如何在表单字段下打印出错误消息 如果出了什么问题?

在这种情况下,最佳做法是什么? 什么提供最好的用户体验?

1 个答案:

答案 0 :(得分:1)

我建议将验证逻辑移到你的模型或formModel,从而保持你的控制器瘦/瘦。

示例:

通用表单模型

abstract class FormModel 
{ 

protected $_errors = array();

//add an error for an attribute if the validation fails
public function addError($attribute, $error) { 
  $this->_errors[$attribute] = $error;
}

//get the error for an attribute
public function getError($attribute) { 
  return (isset($this->_errors[$attribute])) ? $this->_errors[$attribute] : '';
}
//get all errors for all attributes
public function getErrors() {
     return $this->_errors;       
 }

public abstract function load($data);
public abstract function validate();

}

现在,对于您的用户formModel,您可以执行以下操作:

class UserFormModel extends FormModel 
{
   public $firstName;
   public $lastName;
   public $email;
   public $password;

   public function load($data) {
      //you could use the filter_var function to read the values form the $data array. this is just an example
      $this->firstName = $data['reg-form-first-name'];
      $this->lastName = $data['reg-form-last-name'];
      $this->email = $data['reg-form-email'];
      $this->password = $data['reg-form-password'];
   }

   //this is where your form validation logic goes
   //return true if all fields are valid or false if a validation fails
   public function validate() {

       //for example
       if(empty($this->firstName)) { 
         $this->addError('firstName', 'Your first name is required');
         return false;
       }
       return true;
   }
}

现在在您的控制器中,您可以执行以下操作:

class RegistrationController extends Controller {

public function __construct($data = array()) {
    parent::__construct($data);
}

public function index() {
    // form fields are correctly filled in

    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        $formModel = new UserFormModel();
        $formModel->load($_POST); 
        if($formModel->validate()) { 
         userService = new UserService();
         userService->createNewUser($formModel->firstName,...);
        } else {
           //example
           var_dump($formModel->getErrors());
        }
    }
}
}