pTutorial

New way to learn PHP

PHP 5 Form required field

PHP Required field

In the previous section, we worked with optional field while sometimes application needs to make any field required and create a proper error message to the user. You can make any field (text, radio button, select etc.) required as per need.

HTML text field

 
<body>
<html>
<form name= "" method= "post" action= "process.php" >
Name: <input name= "name" type= "text">
<input type= "submit" name= "Submit" value= "Submit"/>
</form>
</body>
</html>

PHP script for required

  

<?php
if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
$name = stripslashes($name);
$name = htmlspecialchars($name);
if($name == "") 
{
echo "Please enter name first";
}
else
{
echo "welcome to pTutorial".$name;	
}
}
?>

The form will not submit until the data will be entered. You can also use an empty function to check field is empty or not as shown below.

Required using empty function

  

<?php
if(isset($_POST['Submit']))
{
$name=trim($_POST["name"]);
if(empty($name)) 
{
echo "Please enter name first";
}
else
{
echo "welcome to pTutorial".$name;	
}
}
?>

You can use an empty function instead of a blank string, it's also a very simple to use, as shown above.

Required radio button HTML

  
<body>
<html>
<form name="info"  method= "post" action= "" >
Male<input type="radio" name="n" value="male">
Female<input type="radio" name="n" value="female">
<input type="submit" name="S">
</form>
</body>
</html>

Required radio button script

  
<?php

if(isset($_POST['S']))
{
$name1=@trim($_POST['n']);

if($name1=="" ) 
{
echo "error";
}
else
{
echo"correct
"; echo "$name1"; } } ?>

Here is a simple PHP script to validate radio button. In this script, we will try to make radio button required.

Required select option

You can also make the select field required with the help of PHP like others. Using an empty function and without empty function.

HTML for select option

 
<body>
<html>
<form action="#" method="post">
<select name="fruits">
<option value="Select one" disabled="disabled"></option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Orange">Orange</option>
</select>
<input type="submit" name="sub" value="Select" />
</form>
</body>
</html>

PHP select option script

  
<?php

if(isset($_POST['sub']))
{
$fruit=trim($_POST["fruits"]);
if($fruit == "") 
{
echo "Please select fruit";
}
else
{
echo "Your favourite fruit is ".$fruit;	
}
}

?>

You can also validate select option easily by using an empty function or a blank string.


QUOTES OF THE DAY

Wonder is the first cause of philosophy.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER