如何使用面向对象技术验证PHP中的表单字段 [英] How to validate form field in PHP using Object Oriented Technique

查看:179
本文介绍了如何使用面向对象技术验证PHP中的表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类'validate'来验证两个字段,即'firstname'和'lastname'。它不能正常工作,当字段为空时显示错误,但当我使用非空字段提交表单时,错误仍然存​​在。

 <?php 

类验证{

public $ firstName,$ lastName,$ errorFirstName ='',$ errorLastName ='';

函数__constructor($ fName,$ lName){
$ this-> firstName = $ fName;
$ this-> lastName = $ lName;


函数check(){

if($ _ SERVER [REQUEST_METHOD] ==POST){
if(empty( $ this-> firstName)){
$ this-> errorFirstName ='名字是必需的';
} else {
$ this-> errorFirstName ='Input is okay';


if(empty($ this-> lastName)){
$ this-> errorLastName ='需要姓氏';
} else {
$ this-> errorLastName ='输入可以';




$ obj =新验证($ _ POST ['firstname'],$ _POST ['lastname']) ;
$ obj-> check();
$ errorF = $ obj-> errorFirstName;
$ errorL = $ obj-> errorLastName;

?>

<!DOCTYPE html>
< html lang =en-USdir =ltr>
< head>
< title>主页< / title>
< meta charset =UTF-8/>
< / head>
< body>
< form method =POSTaction =<?php echo $ _SERVER [PHP_SELF]?>>
< label>名字:< / label>
< input type =textname =firstnameplaceholder =John/>
< p class =error><?php echo $ errorF;?>< / p>
< label>姓氏:< / label>
< input type =textname =lastnameplaceholder =Doe/>
< p class =error><?php echo $ errorL;?>< / p>
< input type =submit>
< / form>
< / body>
< / html>


解决方案


总是会生成数据库类和验证类。 Ehh .... whaaaaay?


不要创建验证类。它从来没有工作。用于验证用户输入的最.. emm ...可持续选项包括:
$ b


  • 在域实体中执行验证

  • 使用值对象



通过使用实体进行验证,它非常简单。在你的情况下,你会有类 Profile ,你有方法 setFirstName(string $ name)。然后在这个方法中,你做了验证,并在错误抛出一个自定义的异常 ,像 InvalidFirstName ..或类似的东西。



使用值对象是一个有点棘手,但它可以防止代码重复。例如,您需要验证电子邮件地址。因此,您希望使用它的方式如下所示:

 尝试{
$ profile = new Profile ;
$ profile-> setEmail(new EmailAddress($ _ POST ['email']));
} catch(InvalidArgumentException $ e){
//验证失败
}


$ b $因此,为了获得这种行为,你应该有这样的类定义:

  class EmailAddress 
{
private $ email;

$ b public function __construct(int $ emailId = null,string $ email = null)
{
if(!$ this-> isValid($ email) ){
抛出新的InvalidArgumentException('无效的电子邮件地址');
}
$ this-> email = $ email;


$ b私有函数isValid($ email)
{
return filter_var($ email,FILTER_VALIDATE_EMAIL)!== false;
}


public function __toString()
{
return $ this-> email;






这种方法更具表现力,在与持久层进行交互时成为一个巨大的缺陷。



实际上,最好的选择是将这两种解决方案结合使用:


  • 在实体中保留验证,对于唯一的规则

  • 使用值对象来重复约束


I have created a class 'validate' to validate two fields i.e 'firstname' and 'lastname'. It is not working fine, it is showing error when field is empty but when I submit the form with non-empty fields the error is still there. How to execute this on form submission?

 <?php

  class validation {

  public $firstName, $lastName, $errorFirstName = '', $errorLastName = '';

  function __constructor($fName, $lName){
    $this->firstName = $fName;
    $this->lastName = $lName;
  }

  function check(){

      if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(empty($this->firstName)){
        $this->errorFirstName = 'First name is required';
       } else {
        $this->errorFirstName = 'Input is okay';
       }

     if(empty($this->lastName)){
         $this->errorLastName = 'Last name is required';
      }  else {
       $this->errorLastName = 'Input is okay';
      }
    }
   }
  }

 $obj = new validation($_POST['firstname'], $_POST['lastname']);
 $obj->check();
 $errorF = $obj->errorFirstName;
 $errorL = $obj->errorLastName;

 ?>

  <!DOCTYPE html>
  <html lang = "en-US" dir = "ltr">
   <head>
    <title>Home</title>
    <meta charset = "UTF-8"/>
   </head>
   <body>
   <form method = "POST" action="<?php echo $_SERVER["PHP_SELF"]?>">
    <label>First Name: </label>
    <input type = "text" name = "firstname" placeholder = "John"/>
    <p class = "error"><?php echo $errorF;?></p>
    <label>Last Name: </label>
    <input type = "text" name = "lastname" placeholder = "Doe"/>
    <p class = "error"><?php echo $errorL;?></p>
    <input type="submit">
   </form>
  </body>
 </html>

解决方案

Everyone always makes "database class" and "validation class". Ehh .... whaaaaay?

Don't make a validation class. It never works. The most .. emm ... sustainable options for validating user input are:

With using entities for validation, it is quite simple. In your case you would have class Profile where you have method setFirstName(string $name). Then within this method you do the validation and on error throw a custom made exception, like InvalidFirstName .. or something like that.

Using value objects is a bit trickier, but it prevents the code duplication. For example, you need to validate email address. So, the way you would want to use it would look something like:

try {
    $profile = new Profile;
    $profile->setEmail(new EmailAddress($_POST['email']));
} catch (InvalidArgumentException $e){
    // validation failed
}

Therefore, to get this behavior, you would have the class defined kinda like this:

class EmailAddress
{
    private $email;


    public function __construct(int $emailId = null, string $email = null)
    {
        if (!$this->isValid($email)) {
            throw new InvalidArgumentException('Not valid email address');
        }
        $this->email = $email;
    }


    private function isValid($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }


    public function __toString()
    {
        return $this->email;
    }
}

This approach is a lot more expressive, but it tends to become a big gnarly, when interacting with persistence layer.

In practice, the best option is to use combination of these both solutions:

  • keep the validation in entities, for rules, that are unique
  • use value objects for often repeating constraints

这篇关于如何使用面向对象技术验证PHP中的表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆