<!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=utf-8" />
<title>Untitled Document</title>
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$error=array();
if(empty ($username)||empty ($password))
{
$error[]="Both the fields must be filled";
}
else {
if(!preg_match("/^[A-Za-z0-9]$/", $username))
{
$error[] = "Invalid username(only alphanumeric characters allowed)";
}
if(strlen($password)<8)
$error[]="Password must be atleast 8 chars";
}
}
?>
</head>
<body>
<form action="" method="post">
Username: <br/><input type="text" name="username" /><br/>
Password: <br/><input type="password" name="password" />
<input type="submit" value="SUBMIT" name="submit" />
<?php
echo "<br/>The following errors occured";
foreach($error as $err)
echo "<p><b>".$err ."</p></b>";
?>
</form>
</body>
</html>
First we check whether the form is submitted or not using isset($_POST['submit']). If it is, its checked if any of the fields are empty. Then we use regular expressions to check whether the username and password meetour criteria i.e, the username should be alphanumeric and the password must be at least 7 characters. We store these errors in an array variable called $array. The errors are outputted inside the HTML rather than from the top of the page as best practice. It is easy to do an email verification also using FILTER_VAR.
No comments:
Post a Comment