pTutorial

New way to learn PHP

PHP 5 text field validation

Text field validation

In this section, we will learn text field validation like fixed length, must be numeric, must be an alphabet.

HTML Form

Name:
 

HTML for all script


<table width= "327" border= "1" align="center" >
<tr>
<td width= "82" >Name: </td>
<td width= "238" ><input name= "name" type= "text"></td>
</tr>
<tr>
<td> </td>
<td><input type= "submit" name= "Submit" value= "Submit" /></td>
</tr>
</table>

Length must be more than five and less than twenty

<?php

if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
$a=strlen($name);
if($a > 5 && $a < 20)
{
echo "You are enter : ". $name;	
}
else
{
echo " Length must be greater than four";	

}
}
?>

In this example first calculate the length of entered string with the help of strlen function and after that check with the help of if condition.

You can change the condition, according to your need like must be ten or anything.

Special symbol not allowed

if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
if(ctype_alnum($name)==false ) 
{
echo " Error ";
}
else
{
echo " Correct ";	
}
}

In this example, ctype_alnum function is used to check entered string must be alphanumeric. With the help of that function, you can also validate for the special symbol, as shown above.

Alphabet must be in capital letter

if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
if(ctype_upper($name)==false ) 
{
$error= "Error :must capital.";
echo "Error";
}
else
{
echo "Correct";	
}
}

You can validate your text field that takes only Capital letter with the help of ctype_upper() function. It returns true if entered string is in capital letters otherwise returned false.

Must be numeric

<?php
if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
if(is_numeric($name)==false)
{
	echo " Error: Must be numeric. ";
}

else
{
echo "correct";	
}
}

?>

Is_numeric() function is used to check whether entered data or variable value is numeric if it is numeric return true otherwise false.

Mobile number validation

if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
if(strlen($name)==10)
{
echo "correct";	
}
else
{
echo "5 error";	

}
}

To validate mobile number, use strlen function that return length of the given string and after that you can validate. In case of mobile number validation, it must be ten.


QUOTES OF THE DAY

Crafty men condemn studies, simple men admire them, and wise use them.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER