How to use regular expression for form validation

Friday, May 18, 2012 0 comments
Suppose, you want user to enter data, combination of small letter,capital letter and digit then how would you do that.You can use regular expressions to check whether user input contains required data or not i.e. digit,small letters.

We have to learn first Perl Compatible Regular Expression (PCRE) in-order to understand this if you are unaware of the PCRE try this out.
PCRE helps us to check the user input with all the combinations of the strings that matches the defined rule.

The given below code will check whether user input  is the combinations of small letter,capital letter and digit. If any one is missing it will echo the message saying that the required data is missing.
Here's the code to do that
<..php

$satisfied=true;
if(isset($_POST['password']))
{
$user_input=$_POST['password'];
/*
Here we check whether user input contains digit or not
*/
$digit="/\d/";
if(!preg_match($digit,$user_input))
{
echo "User input doesnot contains digit
";
$satisfied=false;
}

/*
Here we check whether user input contains capital letter
*/
$capital_alphabet="/[A-Z]/";
if(!preg_match($capital_alphabet,$user_input))
{
echo "User input  doesnot contains Capital letter
";
$satisfied=false;
}

$small_alphabet="/[a-z]/";
if(!preg_match($small_alphabet,$user_input))
{
echo "User input doesnot contains small letter
";
$satisfied=false;
}

$space="/\s/";
if(preg_match($space,$user_input))
{
echo "User input contains Space
";
$satisfied=false;
}

if($satisfied)
{
echo " Satisfied All condtitons";
}
}

?>

0 comments:

Post a Comment

Recent Posts

WebInfo

 

©Copyright 2011 WebInfo