Required field display error message on form

2019-08-10 04:35发布

问题:

I have a form that I need to have required fields filled out. I know to use the code below to verify if the field is blank:

<?php
if  (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>

My question is, how do I get the error message to display on the form page, saving all the data already entered in the form. Example: I fill out all 15 fields on the form, excluding the required field. When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.

I am not sure on the code to do that, or where to put it. On the form, or on the script that executes the form?

回答1:

use client side javascript validation first, then php server side validation.



回答2:

Why you use !empty you can use empty for best result like

<?php
if  (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>

Actually you should be first set HTML5 validation like

<input type="text" name="abc" required="">

You can set custom error message for required field like

<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">

Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.

Thanks.



回答3:

Without knowing the structure of your pages, it's hard to give an exact answer, but here's a general process flow that should help:

  • Form is submitted to processor
  • Processor validates inputs
  • if inputs are good, processor redirects to next page
  • if inputs are not good, processor should send error text and form data back to the routine that builds/displays the form.

IMHO, the processor should not echo anything. All display should be handled by the script that builds the form.

Without coding it for you, that's the best answer I can give :-)