How to display error messages?
To display error messages, we add this code below the input tags in the HTML snippet. If the nameError string is empty, then the error will not be rendered on to the view.
<small>* <?php echo $errorString;?></small>
You can also try this code with Online PHP Compiler
Run Code
Validating each type of field
We need to add more checks if the field is not empty inside of the ‘else’ condition following an empty check.
Name field
The condition written below adds a check for the name to include only dashes, apostrophes, letters and whitespaces.preg_match is the function used to match the pattern. Error message is generated if the pattern does not match the name.
if(!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameError = "only alphabets and letters";
}
You can also try this code with Online PHP Compiler
Run Code
Email field
Below is the condition written to match email with general email pattern.filter_var filters the variable “email” in order to validate with general email pattern. If the filter_var returns false, invalid email format message is logged.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid format";
}
You can also try this code with Online PHP Compiler
Run Code
Profile link
Like we used preg_match in the name field, a website link must match link pattern and then store the message as link not valid if found unmatched with the general pattern.
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteError = "link not valid";
}
You can also try this code with Online PHP Compiler
Run Code
As the other fields can be any text, so we do not do any validation in them.
Example
<!DOCTYPE HTML>
<html>
<body>
<?php
$nameError = $emailError = $slotError = $websiteError = "";
$name = $email = $slot = $message = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input_data($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameError = "only alphabets and letters";
}
}
if (empty($_POST["email"])) {
$emailError = "email is a required field";
} else {
$email = test_input_data($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid format";
}
}
if (empty($_POST["website"])) {
// do nothing
} else {
$website = test_input_data($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input_data($_POST["comment"]);
}
if (empty($_POST["slot"])) {
$slotError = "slot is required";
} else {
$slot = test_input_data($_POST["slot"]);
}
}
function test_input_data($info) {
$info = trim($info);
$info = stripslashes($info);
$info = htmlspecialchars($info);
return $data;
}
?>
<p><small >* required field</small></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<small >* <?php echo $nameError;?></small>
<br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<small >* <?php echo $emailError;?></small>
<br>
Profile Link: <input type="text" name="website" value="<?php echo $website;?>">
<small ><?php echo $websiteError;?></small>
<br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br>
slot:
<input type="radio" name="slot" <?php if (isset($slot) && $slot=="morning") echo "checked";?> value="morning">morning
<input type="radio" name="slot" <?php if (isset($slot) && $slot=="evening") echo "checked";?> value="evening">evening
<small >* <?php echo $slotError;?></small>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code
When we submit only the empty fields, the output will be like the following:
Output
If we submit an invalid link to profile, the output will be like the following:
Output
If we submit an invalid email format, we will receive the following output:
Output
Frequently Asked Question
- What is stripslash and trim?
Ans: It removes backslashes added to the string. It is used to remove slashes when sending form fields via the htmlspeacialchars function. Trim does a similar thing by eliminating the whitespaces from the string.
- Can we customize PHP form fields validations?
Ans: Yes! You can add logic to the validatory function and display the message accordingly. The logic can be anything as per your need.
- What is preg_match and filter_var?
Ans: It is used for regex matching purposes. PHP provides this in-built functionality. The function returns true if the pattern matches correctly; otherwise false. In this article, we used preg_match to match the website link pattern.
Filter_var is used to filter a variable to validate it.
Key Takeaway
Congratulations on getting through both parts of PHP forms. We learnt about setting up the PHP form fields, specify the validations, and to show up error messages in PHP forms. We also saw how to create custom validation for any input type.
If you’re directly here on this blog then you can visit the first part of the blog PHP Forms Part 1 where you can learn about how Forms are validated in PHP.
Happy Learning!