我怎么能这样做? PHP5表单验证

时间:2012-07-24 16:02:54

标签: php

我正在努力设置我的第一步进入OO PHP世界。我正在尝试做的是创建一个验证我的表单输入的类。我知道在我的整个网站中需要哪些输入字段并想要切换,根据输入字段做正确的事情。假设我们有一个名为'email'的输入字段,我们有一个表格等等......

首先,我想要做的是尝试使用array_key()函数读取$ _post名称,基于我有一个开关。

这是我的代码:

public function __construct ( $var ) {
     $this->arraykeys = array_keys($var);
     $this->error = false;
     $this->message = array();   
}        

public function check() {   

      foreach ($this->arraykeys as $i => $value)
      {

      switch ($value)
      {
        case 'email' :

        $checkmail = new checkEmail($_POST);
        $checkmail->chkEmail($_POST['email']);
        if ($checkmail->chkEmail($_POST['email']) == false)
        {
            array_push($this->message, 'Cannot validate emailadres');
        }            
        break; 

      }


      }

     // print_r($this->field);
}

检查有效,但是错误后消息数组会以某种方式保持为空! 我尝试了一切,但我无法将它传到屏幕上!

请帮忙!

谢谢!

2 个答案:

答案 0 :(得分:1)

在使用OOP之前,您实际上需要一些更基本的对象,使您能够让表单处理生效,例如PHP超级全局中的表单字段的面向对象验证,并显示错误消息:

只是示范:

// defining the interfaces and classes of the form values and validation, form field 
// and fields
Interface FormValue
{
    public function getValue();
}

interface FormValueValidator
{
    /**
     * @param FormValue $value
     * @return bool
     */
    public function validate(FormValue $value);
}

class NamedFormValue implements FormValue
{
    private $name;
    private $value;

    public function __construct(array $data, $name, $default = null)
    {
        $this->name = $name;
        $this->value = isset($data[$name]) ? $data[$name] : $default;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function getName()
    {
        return $this->name;
    }
}

class EmailValidator implements FormValueValidator
{
    public function validate(FormValue $value)
    {
        $result = filter_var((string) $value->getValue(), FILTER_VALIDATE_EMAIL);
        return is_string($result);
    }
}

class FormFieldFactory
{
    /**
     * @param $name
     * @param array $field
     * @return FormField
     */
    public function create($name, array $field)
    {
        $validatorClass = sprintf('%sValidator', @$field['validator']);
        $validator = new $validatorClass;

        $formField = new FormField($name);
        $formField->setValidator($validator);
        $formField->setErrorMessage($field['error_msg']);
        return $formField;
    }
}

class FormField
{
    private $name;
    /**
     * @var FormValueValidator
     */
    private $validator;
    private $errorMessage;
    /**
     * @var FormValue
     */
    private $value;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function setValidator(FormValueValidator $validator)
    {
        $this->validator = $validator;
    }

    public function isValid()
    {
        return $this->validator->validate($this->value);
    }

    public function setErrorMessage($errorMessage)
    {
        $this->errorMessage = $errorMessage;
    }


    public function getErrorMessage() {
        return $this->errorMessage;
    }

    public function setValue(FormValue $value)
    {
        $this->value = $value;
    }

    /**
     * @return FormValue
     */
    public function getValue()
    {
        return $this->value;
    }
}

class FormFields extends IteratorIterator
{
    private $fieldFactory;
    private $invalidFields;

    public function __construct(array $definitions, $fieldFactory)
    {
        parent::__construct(new ArrayIterator($definitions));
        $this->fieldFactory = $fieldFactory;
    }

    public function current()
    {
        $name = $this->getInnerIterator()->key();
        $definition = $this->getInnerIterator()->current();
        return $this->fieldFactory->create($name, $definition);
    }

    public function valid()
    {
        return $this->getInnerIterator()->valid();
    }

    /**
     * @param array $data
     * @return bool true on success, false on validation error
     */
    public function validateOn(array $data)
    {
        $this->invalidFields = array();

        foreach($this as $name => $field) {
            /* @var $field FormField */
            $value = new NamedFormValue($data, $name);
            $field->setValue($value);
            $valid = $field->isValid();
            $valid || ($this->invalidFields[$name] = $field);
        }

        return 0 === count($this->invalidFields);
    }

    /**
     * @return FormField[]
     */
    public function getInvalidFields()
    {
        return $this->invalidFields;
    }
}

// defining the form in array notation:
$form = array(
    'fields' => array(
        'email' => array(
            'validator' => 'Email',
            'error_msg' => 'Cannot validate emailadress',
        ),
    ),
);

// processing the form validation
$messages = array();
$fields = new FormFields($form['fields'], new FormFieldFactory());
$fields->validateOn($_POST)
foreach ($fields->getInvalidFields() as $field) {
    $messages[] = $field->getErrorMessage();
}
var_dump($messages);

示例性输出:

array(1) {
  [0]=>
  string(27) "Cannot validate emailadress"
}

答案 1 :(得分:0)

请改为尝试:

public function check()
{   

      foreach ($this->arraykeys as $i => $value)
      {

      switch ($value)
      {
        case 'email' :

        $checkmail = new checkEmail($_POST);
        $checkmail->chkEmail($_POST['email']);
        if ($checkmail->chkEmail($_POST['email']) == false)
        {
            $this->message[] = 'Cannot validate emailadres';
        }            
        break; 

      }


      }

     print_r($this->message);
}

还要确保您的财产设置为公开。

您确定$checkmail->chkEmail()是假的并且运作良好吗?