Tuesday, July 3, 2012

PHP validiate HTML form



We can use PHP or JavaScript to validate the HTML form.
In PHP, when a form is submitted,   we can check if the $_POST value is empty. If not, the MySQL database will be upadated.
PHP Example to validate HTML form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="course_form">
<div class="row required">
<label for="uri">Credit card processing location URL </label><br/>
<input type="text" name="uri" value="<?php echo $row['uri'] ?>" id="uri" size="80" />
</div>
<div class="row required">
<label for="vendor_id">Vendor ID assigned by credit card payment service </label><br/>
<input type="text" name="vendor_id" value="<?php echo $row['vendor_id'] ?>" id="vendor_id" size="40"/>
</div>
<input type="hidden" name="course" value="mycouse" />
<input type="submit" class="input-button" name="submit" value="Save" />
</form>
<?php 
//Note here I used hidden variable to check if the form is submitted, the same as 
// if(isset($_POST['submit']))

if (isset($_POST['course'])) {

if((!$_POST['uri'])&&(!$_POST['vendor_id'])){

//update database hereh

}else{
echo "You need to fill all the required field";
}
?>


JavaScript Example to validate HTML form:
 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validateForm()"   name="course_form">

<div class="row required">
<label for="uri">Credit card processing location URL </label><br/>
<input type="text" name="uri" value="<?php echo $row['uri'] ?>" id="uri" size="80" />
</div>
<div class="row required">
<label for="vendor_id">Vendor ID assigned by credit card payment service </label><br/>
<input type="text" name="vendor_id" value="<?php echo $row['vendor_id'] ?>" id="vendor_id" size="40"/>
</div>
<input type="hidden" name="course" value="mycouse" />
<input type="submit" class="input-button" name="submit" value="Save" />
</form>
 <script type="text/javascript">
 function validateForm()
{
var x=document.forms["course_form"]["uri"].value;
var x=document.forms["course_form"]["vendor_id"].value;
if (x==null || x==""||y==null || y=="")
  {
  alert("You need to fill all the required field");
  return false;
  }
}
</script>

No comments:

Post a Comment