Search code examples
phpformssubmitrequired

Required field display error message on form


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?


Solution

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