PHP Form Validation And Required Field :– Web application are more vulnerable if you do not validate your form inputs.So form validation is used to prevent cross site scripting attacks from hackers.
There are two types of validations in php.
- Client Side Validation
- Server Side Validation
PHP Form Validation | Example
Server side validation is done on php enabled server whereas client side validation usually happens on client side i.e browser.Following below examples describes how does script checks and validate user inputs in form validation process.
When user leaves Name field blank in first example below ; user gets one warning message .Similarily in below example you can easily see if user gives an invalid email address immediately a message displays saying “Please enter valid email id “.
These example contains complete validation script for form data with name ,email , URL fields and radio button.
If you run below script you will find output same as looking in below screenshots.
.
Example.
<?Php $name = $email = $gender = $website = $emailerror=$nameError=""; /*if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameError = "Only letters and white space allowed"; }*/ if(isset($_POST['submit'])) { if (empty($_POST["name"])){ $nameError = "Warning!Name is required"; } else { $name = test_input($_POST["name"]); // check name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameError = " <br?>Only letters and white space allowed"; } } if (empty($_POST["email"])){ $emailerror = "email is required"; } else { $email = test_input($_POST["email"]); // check name only contains letters and whitespace if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailerror = " <br/>please enter correct email id"; } } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; }else { $gender = test_input($_POST["gender"]); } if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } function test_input($value) { $value = trim($value); $value = stripslashes($value); $value = htmlspecialchars($value); return $value; } ?>"; echo " "; echo $email; echo " "; echo $website; echo " "; echo $gender; echo $nameError; echo $emailerror; ?> |