Tutorial – PHP Required Fields
Tutorial – PHP Required Fields
PHP Required Fields
A "Required Field" is a field that must be filled in with value before submission of a form. Required field sometimes known as Mandatory field or Compulsory field.
As with all HTML5 in-browser data validation, required should primarily be seen as a UI helper. A malicious user can easily submit a form request that includes or excludes whatever data they want. Data validation and sanitization need to occur on the server, once the data is received.
To make a field as required field is fairly simple, you are only required to add a "required" boolean attribute into your input element.
< form>
< label for="movie">What is your favorite movie : < /label>
< input name="name" type="text" required />
< input name=”email” type=”text”required/>
< input type="submit" value="Submit"/>
< /form>
We can also add an if else statement for each $_POST variable at server side. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
< ?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
In HTML form if fields are empty than it will automatically shows required red box, as shown in below figure.
For PHP, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields).
Example:-
Posted on Utopian.io - Rewarding Open Source Contributors

Oo very nice tutorial once more!
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
thanks alot!
Hey @brothermic I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x