Blog » PHP » form validation using php

form validation using php

In This script will show you construct and validate a simple form using HTML and PHP. I have added two input filed where name and email here. user can not be submitted empty filed.when the user clicked on submit button, displays error messages, These inputs will be validated to ensure, for example, that the user has been entered their name and valid email address. if the omissions or error, therefor we can check user real information added or not.

Completed source code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>form validation</title>
</head>
<body>
<?php
function validate_input($text){
$text = trim($text);
$text = stripslashes($text);
$text = htmlspecialchars($text);
return $text;
}

$nameErr = $emailErr = "";

if($_SERVER['REQUEST_METHOD'] == "POST"){

$valid = true;

//required field validation
if(empty($_POST['txtName'])){
$nameErr = "Name is required<br/>";
$valid = false;
}else{
$name = validate_input($_POST['txtName']);
}

//required field validation
if(empty($_POST['txtEmail'])){
$emailErr = "Email is required";
$valid = false;
}else{
$email = validate_input($_POST['txtEmail']);
}

//validating email
if(!filter_var($_POST['txtEmail'], FILTER_VALIDATE_EMAIL)){
$emailErr = "Email is incorrect!";
$valid = false;
}else{
$email = validate_input($_POST['txtEmail']);
}

if($valid){
echo "Welcome $name<br/>";
echo "Your email is $email";
}
}
?>

<form id="form1" name="form1" method="post" action="formValidation.php">
Name:
<input name="txtName" type="text" id="txtName" />
<?php echo $nameErr; ?>
<br />
Email:
<input name="txtEmail" type="text" id="txtEmail" />
<?php echo $emailErr; ?>
<br />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
ARTICLE POSTED BY : Admin

Hi, I'am k.g uththara. I'm a professional web developer. I write blog posts in my free time. if you want to contact me, send a message on contact page, thanks.