duanci6484 2012-07-02 21:09
浏览 54
已采纳

通过验证创建完美的表单

On my website I have plenty of form and fields, I have a system that works perfectly but is really painful and to get up and running.

This is what my system does, once you send the form all the info is sent to a class which possesses all the data and validates it. It also stores the value of the field like this $_SESSION['userUpdate']['firstName'][1] = $firstName;

If there is an error it creates a session variable like this $_SESSION['userUpdate']['firstName'][0] = 1; the 1 tells that the field was empty. If there is no error the session variable would be at 0.

If no errors where found in the validation process the data is sent to the database.

After that the form page is reloaded with :

header( 'HTTP/1.1 303 See Other' );
header( 'Location: '.curPageURL().'' ); 

I use that so that you cannot resend the data when reloading the page. That is the reason I'm using all these session variables.

Then with a lot of it/else if/else I check the values of the session variables and output errors and also populate the form with the data entered previously.

Let me show you an example for a firstname field.

This is the HTML code :

<label for="firstName" class="block">First Name</label>
<span>Your first name goes here.</span><?php echo $text_first_name ?>
<input type="text" id="firstName" class="mediaText" name="firstName" value="<?php echo $first_name2; ?>" onchange="needToConfirm=true" <?php echo $style_first_name ?> />

This is the validation process by the class :

$_SESSION['ui']['first_name'][1] = $this->first_name; 
if (isset($this->first_name)) 
    {
        if($this->first_name == NULL)
        {
            $_SESSION['ui']['first_name'][0] = 1;
        }
        else if(minRange(3, $this->first_name)) 
        {   
            $_SESSION['ui']['first_name'][0] = 2; 
        }
        else
        {
            array_push($set, "FirstName = '".$db->sql_escape($this->first_name)."'");
        }
    }

This is the php code that handles the eventual errors :

$error_bg = "style=\"background:#EE5C42\"";

//FIRST NAME
if($_SESSION['ui']['first_name'][0] == 1)
{
    $style_first_name = $error_bg;
    $first_name2 = $_SESSION['ui']['first_name'][1];
}
else if($_SESSION['ui']['first_name'][0] == 2)
{
    $style_first_name = $error_bg;
    $first_name2 = $_SESSION['ui']['first_name'][1];
    $text_first_name = "<span class=\"errorText\">Your first name must consist of at least 3 characters.</span>";
}
else
{
    $first_name2 = $userdetails["FirstName"];
}

At the end of the page there is a little function to unset the session variables.

I am wondering it there is any way to make this simpler and easier to get up and running ?

  • 写回答

2条回答 默认 最新

  • dsgm5631 2012-07-02 21:35
    关注

    If you're asking for code optimization advice, here's how I would do that:

    // so you have bunch of error codes
    $possible_errors = array(
      '0' => '', // No error
      '1' => '', // Error, but no error message
      '2' => 'Your %s must consists of at least 3 characters',
      ...
    );
    
    // then you have form fields stored in session
    // fields in session should be named like the keys in $userdetails
    // 'formName' => array('FirstName' => array(0, 'German'), 'LastName' => array('1', ''))
    $errors = $values = array();
    foreach ($_SESSION['formName'] as $field => $element) {
        if ($element[0] > 0) { // Has error
            $error_code = $element[0];
            $error_message = $possible_errors[$error_code];
            if (!empty($error_message)) {
                $errors[$field] = sprintf($error_message, $field);
            }
        } else {
            $values[$field] = $userdetails[$field];
        }
    }
    
    // in here you end up with two arrays:
    //   - $errors Error messages keyed by field name
    //   - $values Values keyed by field name
    // You use them like this
    <label for="firstName" class="block">First Name</label>
    <span>Your first name goes here.</span><?php if (array_key_exists('FirstName', $errors)) echo $errors['FirstName']; ?>
    <input type="text" id="firstName" class="mediaText" name="firstName" 
      value="<?php echo $values['FirstName']; ?>"
      onchange="needToConfirm=true"
      <?php if(array_key_exists('FirstName', $errors)):?>style="background:#EE5C42"<?php endif;?> />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?