Design html input form with required star field that needs to fill and without it the form will not be submitted.
In this tutorial we are creating a custom html form with different fields like name, email,comments, and like radio button values and after that we are setting up required conditions on name, email and like radio button that user needs to fill/select and without submitting them the form will not submitted. So here is the complete step by step tutorial for Create custom form in PHP with form validation required field.
How to Create custom form in PHP with form validation required field.
Code for custom-php-form.php file.
<!doctype html> <html> <head> <meta charset="utf-8"> <style> .error_message_color_style { color: #f40000; } </style> <title>Custom form in PHP with form validation</title> </head> <body> <?php $NameErrorMessage = $EmailErrorMessage = $GenderErrorMessage = ""; $name = $email = $gender = $address = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $NameErrorMessage = "Please Enter Name"; } else { $name = get_data($_POST["name"]); } if (empty($_POST["email"])) { $EmailErrorMessage = "Please Enter Email"; } else { $email = get_data($_POST["email"]); } if (empty($_POST["address"])) { $address = ""; } else { $address = get_data($_POST["address"]); } if (empty($_POST["gender"])) { $GenderErrorMessage = "Please select Gender"; } else { $gender = get_data($_POST["gender"]); } } function get_data($Value) { //Adding trim function. $Value = trim($Value); //Adding stripslashes function to remove back slash. $Value = stripslashes($Value); //Adding htmlspecialchars function. $Value = htmlspecialchars($Value); return $Value; } ?> <h2>Custom form in PHP with form validation</h2> <p><span class="error_message_color_style">* required field.</span></p> <table> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <tr> <td>Name:</td> <td> <input type="text" name="name"></td> <td><span class="error_message_color_style">* <?php echo $NameErrorMessage;?></span></td></tr> <tr> <td> E-mail: </td> <td><input type="text" name="email"></td> <td><span class="error_message_color_style">* <?php echo $EmailErrorMessage;?></span></td></tr> <tr> <td>Gender:</td> <td><input type="radio" name="gender" value="Male">Male <input type="radio" name="gender" value="Female">Female</td> <td><span class="error_message_color_style">* <?php echo $GenderErrorMessage;?></span></td></tr> <tr> <td>Address: </td><td><textarea name="address" rows="4" cols="30"></textarea></td></tr> <tr><td> <input type="submit" name="submit" value="Submit"> </td></tr> </form> </table> <?php echo "<h2>Result Display Here:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $gender; echo "<br>"; echo $address; ?> </body> </html>
Screenshots: