Regular Expression check, Validation in PHP
In this article, you will find php validation code for:
1) Interger Validation
2) String Validation
3) Decimal Validation (two digits after decimal)
4) Email Validation
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$amount = $_POST['amount'];
// we have used ereg() function for regular expression match
// ereg() function
// Searches a string for matches to the regular expression given in pattern in a case-sensitive way.
// for case insensitive search, we can use eregi() function
// ereg() function will retrun false if no matches were found
//checking name (string)
$check_name = ereg('^[a-zA-Z ]+$',$name);
if($check_name == false)
{
echo "<font color='red'>Invalid name: $name<br/></font>";
}
//checking amount (decimal value, allowing only 2 digits after dot)
$check_amount = ereg('^[0-9]+(\.[0-9]{2})$',$amount);
if($check_amount == false)
{
echo "<font color='red'>Invalid amount: $amount<br/></font>";
}
//checking age (integer)
$check_age = ereg('^[0-9]+$',$age);
if($check_age == false)
{
echo "<font color='red'>Invalid age: $age<br/></font>";
}
//checking email
$check_email = ereg('[a-zA-Z0-9_.]+@[a-zA-Z]+(\.[a-zA-Z]{3}(\.[a-zA-Z]{2})?)?',$email);
if($check_email == false)
{
echo "<font color='red'>Invalid email: $email<br/></font>";
}
//if everything is valid
if($check_name != false && $check_age != false && $check_amount != false && $check_email != false)
{
echo "<font color='green'>Everything is correct.";
echo "<br/>";
echo "Name: $name";
echo "<br/>";
echo "Age: $age";
echo "<br/>";
echo "Amount: $amount";
echo "<br/>";
echo "Email: $email";
echo "<br/>";
echo "</font>";
echo "<br/>";
}
}
?>
<html>
<head>
<title>Regular Expression Test</title>
</head>
<body>
<form method="post" action="regex.php">
<table>
<tr><td>Name: </td><td><input type="text" name="name" /></td></tr>
<tr><td>Age: </td><td><input type="text" name="age" /></td></tr>
<tr><td>Amount: </td><td><input type="text" name="amount" /> (eg. 11.22)</td></tr>
<tr><td>Email: </td><td><input type="text" name="email" /></td></tr>
<tr><td> </td><td><input type="submit" name="Submit" value="Submit" /></td></tr>
</table>
</form>
</body>
</html>
Related posts:
- Fun with Regular Expression
- W3C Validation: IFrame Error with XHTML 1.0 Strict Doctype
- Session Handling in PHP
- How to get(view) html source code of a website
- PHP: Read Write CSV
- How to change the source code and modify/parse a website?
- ASP.NET Error: A potentially dangerous Request.Form value was detected from the client
- Magento: How to check if current page is homepage?
- PHP: Easily send email with PHPMailer
- jQuery: Grey out background and preview image as popup
