简体   繁体   English

PHP - 在错误的时间停止显示通知/错误

[英]PHP - stop the notice/error displaying at wrong time

I accidentally deleted my previous question about this.我不小心删除了我之前关于这个的问题。

I'm new at PHP.我是 PHP 新手。 This is my first assignment.这是我的第一个任务。 I have an error message "Sales price must be a valid amount" that is being displayed next to the first input box that shouldn't be there.我在第一个不应该出现的输入框旁边显示一条错误消息“销售价格必须是有效金额”。 This occurs when the user clicks "confirm" without data in the inputs.当用户在输入中没有数据的情况下单击“确认”时会发生这种情况。 Instructions state that in this case, the user remains on the page.说明指出,在这种情况下,用户将停留在页面上。 I don't need any error messages displaying at this time.我此时不需要显示任何错误消息。 How can I keep my error messages working as they should but stop the one message from showing up when "confirm" is clicked with no input?如何让我的错误消息正常工作,但在没有输入的情况下单击“确认”时停止显示一条消息? Hope this makes sense.希望这是有道理的。

 // get the data from the form $sales_price = filter_input(INPUT_POST, 'sales_price', FILTER_VALIDATE_FLOAT); $discount_percent = filter_input(INPUT_POST, 'discount_percent', FILTER_VALIDATE_FLOAT); $total_price = filter_input(INPUT_POST, 'total_price', FILTER_VALIDATE_FLOAT); if (isset($_POST['confirmSubmit'])) { echo 'Validation Error'; $validation_error = 'Validation Error'; } // validate sales price $sales_valid = true; $sales_priceError = ''; if ($sales_price === NULL) { $sales_priceError = ''; $sales_valid = false; } else if ($sales_price === FALSE) { $sales_priceError = 'Sales price must be a valid amount'; $sales_valid = false; } else if ($sales_price <= 0.0) { $sales_priceError = 'Sales price must be greater than 0'; $sales_valid = false; } // validate discount percent $discount_valid = true; $discount_percentError = ''; if ($discount_percent === NULL) { $discount_percentError = ''; $discount_valid = false; } else if ($discount_percent === FALSE) { $discount_percentError = 'Discount percent must be a valid amount'; $discount_valid = false; } else if ($discount_percent <= 0.0) { $discount_percentError = 'Discount percent must be greater than 0'; $discount_valid = false; } // calculate the discount and the discounted price $discount_amount = $sales_price * $discount_percent / 100; $total_price = $sales_price - $discount_amount; ?> <!doctype html> <html lang="en"> <head> <title>Quote</title> <link rel="stylesheet" type="text/css" href="quote.css"> </head> <body> <section> <h1>Price Quotation</h1> <form id="priceForm" name="priceForm" method="post" action=''> <label for="sales_price">Sales Price </label> <input type="text" id="sales_price" name="sales_price" required value="<?php echo $sales_price; ?>"/> <?php if (!empty($sales_priceError)) : ?> <span style="color:red;background-color: white"> <?php echo $sales_priceError; ?> </span> <?php endif; ?> <br/> <br/> <label for="discount_percent">Discount Percent </label> <input type="text" id="discount_percent" name="discount_percent" required value="<?php echo $discount_percent; ?>"/> <?php if (!empty($discount_percentError)) : ?> <span style="color:red;background-color: white"> <?php echo $discount_percentError; ?> </span> <?php endif; ?> <p class="discount">Discount Amount <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($discount_amount, 2); ?></p> <p class="total">Total Price <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($total_price, 2); ?></p> <input type="submit" class=inline name="submitButton" id="submitButton" value="Calculate"/> </form> <form id="confirmForm" name="confirmForm" method="post" action="<?php echo(($sales_valid && $discount_valid) ? 'confirm.php' : ''); ?>"> <input type="hidden" id="sales_price" name="sales_price" value="<?php echo $sales_price ?>"/> <input type="hidden" id="discount_amount" name="discount_amount" value="<?php echo $discount_amount ?>"/> <input type="hidden" id="total_price" name="total_price" value="<?php echo $total_price ?>"/> <input type="submit" class=inline name="confirmSubmit" id="confirmSubmit" value="Confirm"/> </form> <div> <p> Enter price and discount amount and click Calculate</p> </div> </section> </body> </html>

Ok so you need to structure you form processing logic like this:好的,所以您需要像这样构建表单处理逻辑:

 $sales_price = ''; //default value
 //other fields - I used just this one, but obviously you should do the
 //same/simular for the rest of them

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //do stuff common to both form, such as both have sales_price

    $sales_price = filter_input(INPUT_POST, 'sales_price', FILTER_VALIDATE_FLOAT);

    if(isset($_POST['submitButton'])) {
       //code specific to the first form

       $sales_valid = true;
       $sales_priceError = '';
       if ($sales_price === NULL) {
           $sales_priceError = '';
           $sales_valid = false;
       } else if ($sales_price === FALSE) {
           $sales_priceError = 'Sales price must be a valid amount';
           $sales_valid = false;
       } else if ($sales_price <= 0.0) {
           $sales_priceError = 'Sales price must be greater than 0';
           $sales_valid = false;
       }

        //and so on

    }else if(isset($_POST['confirmSubmit'])){ 
        //code specific to the second form


        if(!empty($sales_price)){
              //do stuff
        }

    }

}

This way when the first form is submitted only that code runs, when the second only that code.这样,当第一个表单提交时只运行该代码,当第二个只运行该代码时。

When isset($_POST['submitButton']) is false its impossible for the validation code to run, and therefor you won't get the error when submitting the other form.isset($_POST['submitButton'])为 false 时,验证代码不可能运行,因此在提交其他表单时不会出现错误。 You should check the data in the second forms processing code, to make sure the first one was sent.您应该检查第二个表单处理代码中的数据,以确保发送了第一个表单。 You can also add a hidden field (into confirm form) that is empty on the first from submission and then filled after when it is submitted.您还可以添加一个隐藏字段(到确认表单中),该字段在第一次提交时为空,然后在提交后填写。

Pro Tip : is you can use a do/while loop as a control structure in the second form processing code like this:专业提示:您是否可以使用 do/while 循环作为第二种形式处理代码中的控制结构,如下所示:

 }else if(isset($_POST['confirmSubmit'])){ 

  do{

    if(empty($sales_price)) break; //bail on the loop


        //form processing code

 }while(false); //runs 1 time

Do while, unlike other loops checks the condition (in the while part) after it runs 1 time. Do while 与其他循环不同,它在运行 1 次后检查条件(在 while 部分)。 In this case that condition is FALSE, so it ends the loop.在这种情况下,条件为 FALSE,因此它结束循环。 But this allows you to use break or continue (break is more logical) to exit the loop and prevent the rest of the code from running.但这允许您使用breakcontinue (break 更合乎逻辑)退出循环并阻止其余代码运行。 This is cleaner then excluding the code by if conditions (IMO).这比 if 条件(IMO)排除代码更干净。

Hope that helps.希望有帮助。

PS - I tried to keep it as simple as I could. PS - 我尽量保持简单。

This occurs when the user clicks "confirm" without data in the inputs.当用户在输入中没有数据的情况下单击“确认”时会发生这种情况。

Based on your codes, I believe what you really need is a simple Javascript form validation prior to submission.根据您的代码,我相信您真正需要的是在提交之前进行简单的Javascript表单验证。 You can add this:你可以添加这个:

<head>
<script>
function validateForm() {

    // check values
    var salesPriceValue = document.forms["priceForm"]["sales_price"].value;
    if (salesPriceValue.length<=0) {
      alert("Please enter Sales Price before submitting the form!");
      return false;
    }
    return true;
}
</script></head>

<body>

<form id="priceForm" name="priceForm" method="post" action='' onsubmit="return validateForm()">
<input type="text" id="sales_price" name="sales_price" required
               value="<?php echo $sales_price; ?>"/>
.. etc

The key is onsubmit function on the form tag.关键是onsubmit的形式标记功能。 You can add more form item validation as needed.您可以根据需要添加更多表单项验证。 I just show example of one input text type.我只展示了一种输入文本类型的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM