saftutorials.com
PHP Form Required

PHP form validation means to check the required input field is filled or not in proper format in the form. In this tutorials you can learn for HTML Form required validation with PHP.

There are two types of validation
Client Side Validation (This validation performed at the client side means client browsers)
Server Side Validation (This validation performed at the server side)

Validation Rules for some input fields

Field - Validation Rules

Name: Name field contain letters and white space only

Email Id: Email Id must contain @ and.

Mobile No: Mobile No contain only numeric values

Dropdown: Must be select at least once

Radio button: Must be select at least once

Check Box: Must be checked at least once


Example for form validation on server side

<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $mobileErr = "";
$name = $email = $gender = $mobile = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
 $nameErr = "Name is required";
}else {
 $name = validate_input($_POST["name"]);
}
if (empty($_POST["email"])) {
 $emailErr = "Email is required";
}else {
 $email = validate_input($_POST["email"]);
 
 // check if email address is invalid
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format"; 
 }
}
if (empty($_POST["mobile"])) {
 $mobileErr = "";
}
else {
 $mobile = validate_input($_POST["mobile"]);
// check if email address is valid
 if (!filter_var($mobile, FILTER_VALIDATE_INT)) {
    $mobileErr = "Invalid mobile no"; 
 }
}
if (empty($_POST["gender"])) {
 $genderErr = "Gender is required";
}else {
 $gender = validate_input($_POST["gender"]);
}
}
function validate_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Registration Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
 <td>Name:</td>
 <td><input type="text" name="name"><span class="error">* <?php echo $nameErr;?></span></td>
</tr>
<tr>
 <td>Email Id: </td>
 <td><input type="text" name="email"><span class="error">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
 <td>Mobile:</td>
 <td><input type="text" name="mobile"><span class="error"><?php echo $mobileErr;?></span></td>
</tr>
<tr>
 <td>Sex:</td>
 <td>
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
    <span class="error">* <?php echo $genderErr;?></span>
 </td>
</tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>




Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic