首页 > 解决方案 > 表单处理 php

问题描述

我是新来的,所以如果我误解了如何在这里提交问题,请指出正确的方向。

1.我收到警告错误,指出我有“未定义的数组键”。我在提交表格之前和之后得到这个。我已经在顶部定义了数组,所以我不确定为什么它们是未定义的。

2.如果我输入了错误的电话号码格式,我的错误捕获不起作用。我最初收到错误消息,说明以正确的格式输入,但如果我以正确的格式输入信息并提交,我仍然会收到错误消息,并且电话号码会重置为最初的状态。我知道它正在从 $_GET 中提取它,但不确定为什么当它再次提交时它没有更新 $_GET 以正确填充它。


<?php

function validate_field_contents($content, $title, $type, $message, ) {
    if($type == 'text') {
        $string_exp = "/^[A-Za-z0-9._%-]/";
        if(!preg_match($string_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    } 
    elseif($type == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    }
    elseif($type == 'phone'){
        $num_exp = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' in the following format (xxx)xxx-xxxx.</li>';}
        }
    }
    elseif($type == 'zip'){
        $num_exp = "/^[0-9]{5}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' with 5 numbers only.</li>';}
        }
    }
    elseif(empty($_POST['band'])){
            {$message .= '<li>Please select a ' . strtolower($title) . '.</li>';}
    }
    elseif(empty($type == 'color')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'size')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'style')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    return $message;
}
?>

标签: phpformsvalidationerror-handling

解决方案


好的,这里有几件事:

  • 您不需要顶部的变量分配。这在 C 和其他语言中非常重要,但 PHP 不需要这样做。

  • 您的if(isset($_GET['firstName'])) $firstName = $_GET['firstName'];语句正在使用$_GET,而您的<form>标签使用$_POST- 这是您的主要问题

  • 我建议使用变量数组,如下所示:

     $address_vars = array(
      array(
         'element_name' => 'firstName',
         'title' => 'First Name',
         'validation' => 'text',
      ),
      array(
         'element_name' => 'lastName',
         'title' => 'Last Name',
         'validation' => 'text',
      ),
    );
    

然后您可以像这样以编程方式输出字段:

foreach($address_vars as $cur_address_field) {
    ?>
        <label><?php echo $cur_address_field['title']; ?>: <input type = "text" value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" id = "<?php echo $cur_address_field['element_name']; ?>" placeholder = "<?php echo $cur_address_field['title']; ?>" name ="<?php echo $cur_address_field['element_name']; ?>"></label>
    <?php
}

这不仅大大地清理了代码,而且还使更改/更新甚至添加到字段变得更加容易(并且更安全)。

然后,要验证字段,您可以使用validation我设置为开关的数组键来遍历所有字段。像这样的东西:

foreach($address_vars as $validate_field) {
    if($validate_field['validation'] == 'text') {
        // this is a text-based field, so we check it against the text-only regex
        $string_exp = "/^[A-Za-z .'-]+$/";
        if(!preg_match($string_exp, $_POST[$validate_field['element_name']])) {
            $message .= '<li>Please enter a ' . strtolower($validate_field['title']) . ' containing letters and spaces only.</li>';
        }
    } elseif($validate_field['validation'] == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $_POST[$validate_field['element_name']])) {
            $message .= '<li>Please enter a valid ' . strtolower($validate_field['title']) . '.</li>';
        }
    }
}
  • 您没有正确连接您的产品字段。用户提交的值无法在此处“粘贴”,因此该字段的值完全丢失了。首先,我们可以将这些都放在一个数组中,类似于我们对地址字段所做的操作:

    $product_vars = array( array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => '选择一个', ), array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), );

然后我们可以使用以下形式:

foreach($product_vars as $cur_product) {
    ?>
            <label><?php echo $cur_product['title']; ?>: </label>
                <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                    <option><?php echo $cur_product['placeholder']; ?></option>
                    <?php
                        foreach($cur_product['options'] as $cur_option)
                        {
                            echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                        }
                    ?>
                </select>
    <?php
}

希望这会有所帮助!

**由于共享新代码而进行编辑**

这里又发生了一些事情。主要项目是:$product_varsforeach 在<form>标签之外,<form>标签没有被设置为使用,$_POST尽管其余的代码都是这样设置的,并且没有添加任何验证类型。我已经粘贴了我拥有的完整代码,这对我有用。

<?php
        //arrays
        $bands = array ("ACDC", "Journey", "Modest Mouse", "Band of Horses", "Vampire Weekend", "Of Monsters and Men", "Broken Bells", "Phoenix", "Fleetwood Mac", "AJR",);
        $colors = array ("Black", "Navy", "Red", "Orange", "Pink", "Yellow", "Green", "Gray", "White", "Purple",);
        $sizes = array ("X-Small", "Small", "Medium", "Large", "X-Large", "XX-Large", "XXX-Large",);
        $styles = array ("Tank Top", "T-Shirt", "Long Sleeve", "Hoodie", "Sweatshirt", "Jacket",);
        
        $product_vars = array(
        array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'size', 'title' => 'Size', 'options' => $sizes, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'style', 'title' => 'Style', 'options' => $styles, 'placeholder' => 'Choose One', ), 
        );
    
        $address_vars = array(
        array(  'element_name' => 'firstName', 'title' => 'First Name', 'validation' => 'text',),
        array(  'element_name' => 'lastName',   'title' => 'Last Name', 'validation' => 'text',),
        array(  'element_name' => 'email', 'title' => 'Email Address', 'validation' => 'email',),
        array(  'element_name' => 'phone', 'title' => 'Phone Number', 'validation' => 'phone',),
        array(  'element_name' => 'address', 'title' => 'Address', 'validation' => 'address',),
        array(  'element_name' => 'city', 'title' => 'City', 'validation' => 'text',),
        array(  'element_name' => 'state', 'title' => 'State', 'validation' => 'text',),
        array(  'element_name' => 'zip', 'title' => 'Zip Code', 'validation' => 'zip',),
        );
    
        ?>
        <form action="" method="post">
        <?php
        foreach($product_vars as $cur_product) {
        ?>
                <label><?php echo $cur_product['title']; ?>: </label>
                    <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                        <option><?php echo $cur_product['placeholder']; ?></option>
                        <?php
                            foreach($cur_product['options'] as $cur_option)
                            {
                                echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                            }
                        ?>
                    </select>
        <?php
        }
        foreach($address_vars as $cur_address_field) {
        ?>
    
            <label><?php echo $cur_address_field['title']; ?>: 
                <input 
                type = "text" 
                value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" 
                id = "<?php echo $cur_address_field['element_name']; ?>" 
                placeholder = "<?php echo $cur_address_field['title']; ?>" 
                name ="<?php echo $cur_address_field['element_name']; ?>">  
            </label>
            <?php } ?>
                <input type="reset" class="buttons">
                <input type="submit" class="buttons">
            </form>
        <?php


        foreach($address_vars as $validate_field) {
            $message = validate_field_contents($_POST[$validate_field['element_name']], $validate_field['title'], $validate_field['validation'], $message);
        }
        ?>
    
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>T-Shirt Form</title>
            <link type="text/css" rel="stylesheet" href="css/style-prod.css">
            <script src="..js/script.js" defer></script>
        </head>
        <body>          
    
            <?php
            if($message) {
                echo '<p>'.$message.'</p>';
            } else {
            ?>

            <!--display processed information here-->
            <h3 class="subheaderone">Thank you for your order!</h3><br>
            <h3 class = "subheadertwo">Product:</h3>
            <div class = "output">
            
                <h3 class = "subheadertwo">Shipping & Contact Information:</h3>
                <?php foreach($address_vars as $cur_address) {
                    echo '<p>' . $cur_address['title'] . ': ' . (isset($_POST[$cur_address['element_name']]) ? $_POST[$cur_address['element_name']] : '') . '</p>';
                } ?>
            </div>
            <div class="another"> 
                <nav><a href="./products.php"> Submit Another Form</a></nav> 
            </div>
            <?php } ?>
        </body>
    </html>


<?php

function validate_field_contents($content, $title, $type, $message) {
    if($type == 'text') {
        // this is a text-based field, so we check it against the text-only regex
        $string_exp = "/^[A-Za-z .'-]+$/";
        if(!preg_match($string_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . ' containing letters and spaces only.</li>';
        }
    } elseif($type == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    }
    return $message;
}

推荐阅读