Friday, January 1, 2016

Form Validation with Regular Expression

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation with Regular Expression</title>

</head>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') { // IF form was submitted
$errors = Array(); // Create a blank array
if (0===preg_match("/\S+/", $_POST['fname'])) { 
$errors['fname'] = 'Please enter a first name';
}
if (0===preg_match("/\S+/", $_POST['lname'])) {
$errors['lname'] = 'Please enter a last name';
}
if (0===preg_match("/.+@.+\..+/", $_POST['user_email'])) {
$errors['email'] = 'Please enter a valid Email address';
}
if (0===preg_match("/.{6,}/", $_POST['passwd'])) {
$errors['passwd'] = 'The password you entered was invalid';
}
if(0 !==strcmp($_POST['passwd'], $_POST['confpasswd'])) {
$errors['passconfirm'] = "Password do not match"; 
}
if(0===count($errors)) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['user_email'];
$passwd = $_POST['passwd'];
echo <<<EOD
<h3>Your validated information are as below</h3>
<p>First name: $fname</p>
<p>Last name: $lname</p>
<p>Email address: $email</p>
<p>Password: $passwd </p>
EOD;
} else {
// Error display
echo "<ul>";
foreach($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}

} // IF form was submitted
?>
<div class="myform">
<form method="post" action="">
<fieldset>
<legend>Register with us:</legend>
<p><input class="input" type="text" name="fname" placeholder="First Name" value="<?php if(isset($_POST['fname'])) {echo $_POST['fname'];} ?>"></p>
<p><input class="input" type="text" name="lname" placeholder="Last Name" value="<?php if(isset($_POST['lname'])) {echo $_POST['lname'];} ?>" ></p>
<p><input class="input" type="text" name="user_email" placeholder="Email address" value="<?php if(isset($_POST['user_email'])) {echo $_POST['user_email'];} ?>"></p>
<p><input class="input" type="password" name="passwd" placeholder="Password"></p>
<p><input class="input" type="password" name="confpasswd" placeholder="Confirm Password"></p>
<input type="submit" name="submit" value="Register"><input type="reset" name="submit" value="RESET">
</fieldset>
</form>
</div>
</body>
</html>

No comments:

Post a Comment