form validation library in php

Hi Geeks,

Today i am sharing a generic class for

Form validation library in php

&  it also populate if form validation failed. First of all you can download the ‘form validation library in php’ by clicking on following url.

https://github.com/g10dra/form_validation_php/blob/master/class.validation.php

Now in this class you can validate the require,numeric,file-extension,match password & confirm password,validate url and other validation also.

It is having a validation with database like is_unique in mysql database where you need pass the db connection if you want to user is_unique validation.

Step 1: Include & Initialize the class in header or before your form s following:

//include the form validation class//
require 'class.validation.php'; or any of your path where you have save the class

$db_details=array();//array for db details for validation some fields like is_unique from DB.
//pass the varribale dynamic or static

$db_details['db_host']=DB_HOST;
$db_details['db_user']=DB_USER;
$db_details['db_password']=DB_PASS;
$db_details['db_name']=DB_NAME;


$validation= new validation($db_details);

//

Step 2: Create a HTML FORM

we are assuming that we have a form for add/edit ‘Advertise campaign’ form

Read the full comments in code

 

<div class="content-box-large">
			  				<div class="panel-heading">
					            <div class="panel-title">Add / Update Campaign</div>
					          <?php
							  //this is for getting data for edit mode
					            if(isset($_GET['id']) && $_GET['id']!="")
								{
									$query = "SELECT * from tbl_ads WHERE a_id='".$_GET['id']."' ";
									//we have user a database class for retirving the results ,you  can use your own data retrival process
									if( $database->num_rows( $query ) > 0 )
									{
										$_edited_data = $database->get_results( $query );
										$_edited_data=$_edited_data[0];
									}
									else{
										header("location:campaign.php?err=something bad happen !");
									}
								}
								else
								{
									//add time initialize the blank data in edit data varriable ,if we are add action
									$_edited_data=array();
									$_edited_data['ad_name']="";
									$_edited_data['end_url']="";
									$_edited_data['campaign_type']="";
									$_edited_data['dimension']="";
									$_edited_data['is_active']="";
								
								}
								?>
					        </div>
			  				<div class="panel-body">
			  					<form enctype="multipart/form-data" method="post">
								
								<input type="hidden" name="is_post" value="1" />
								<!-- field for detecting if form is submitted or not -->
								
								<input type="hidden" name="edit_id" value="<?php echo (isset($_GET['id']))? $_GET['id'] : "0"; ?>" />
								<!-- field for detecting if form is submitted in edit or add mode -->
								
									<fieldset>
										<div class="form-group">
											<label>Ad Campaign Name</label>
											<input value="<?php echo $validation->set_val("ad_name",$_edited_data['ad_name']); ?>"  name="ad_name" class="form-control" placeholder="Ad campaign name" type="text">
											
											<?php echo $validation->error_message("ad_name","<span style='color:red'>");
											?>
											
											<!-- 
											$validation->set_val() is having 2 parameter
											1st is a field name and second is for default value or edit mode populated value.//This method used to populate the text field value
											
											$validation->error_message() is having 2 params first is the field name and second is the opening tag of html tag where error should show in designed form,do not clode the tag it will autoclose the opened tag passed over it.
											
											-->
											
										</div>
										<div class="form-group">
											<label>Target url</label>
											<input value="<?php echo $validation->set_val("end_url",$_edited_data['end_url']); ?>"  name="end_url" class="form-control" placeholder="Target Url" type="text">
											
											<?php echo $validation->error_message("end_url","<span style='color:red'>");
											?>
											
										</div>
										<div class="form-group">
											<label>Creative Banner</label>
											<input class="form-control" name="ad_media_file" type="file" >
											
											<?php 
											if(isset($_edited_data['ad_media_file']) && $_edited_data['ad_media_file']!="")
											{
												echo '<img style="max-width:300px;height:auto" src="AD_MEDIA/'.$_edited_data['ad_media_file'].'"   />';
											}
											
											echo $validation->error_message("ad_media_file","<span style='color:red'>");
											?>
										</div>
										<div class="form-group">
											<label>Campaign Type</label>
											
											<select <?php  if(isset($_GET['id']) && $_GET['id']!=""){ echo "disabled"; } ?> name="campaign_type" class="form-control input-md">
													<option <?php echo $validation->set_select("campaign_type","1",$_edited_data['campaign_type']); ?> value="1">CTR (Click basis)</option>
													<option <?php echo $validation->set_select("campaign_type","2",$_edited_data['campaign_type']); ?> value="2">CPM (impression every 1k)</option>
												</select>
												
												<!--
												
												$validation->set_select() is having 3 params for first is field name second is 
												for seting selected=selected if value matched in failed post, and third is for seleted by default in edit mode
												-->
												
										</div>
										 
												
										</div>
										<div class="form-group">
											<label>Ad Campaign Status </label>
											
											<select  name="is_active" class="form-control input-md">
													<option <?php echo $validation->set_select("is_active","1",$_edited_data['is_active']); ?> value="1">Enabled</option>
													<option <?php echo $validation->set_select("is_active","0",$_edited_data['is_active']); ?> value="0">Disabled</option>
												</select>
												
										</div>
										
									</fieldset>
									<div>
										<button type="submit" class="btn btn-primary">
											<i class="fa fa-save"></i>
											Submit
										</button>
									</div>
								</form>
			  				</div>
			  			</div>

Step 3: Create a Table for advertise add/edit using following sql dump

CREATE TABLE IF NOT EXISTS `tbl_ads` (
  `a_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `ad_name` varchar(255) NOT NULL,
  `ad_media_file` text NOT NULL,
  `end_url` tinytext NOT NULL,
  `total_impression` int(11) NOT NULL,
  `campaign_type` enum('1','2') NOT NULL COMMENT '1 for click base 2 for impression',
  `is_active` enum('0','1') NOT NULL DEFAULT '1',
  `approved` enum('0','1') NOT NULL DEFAULT '0',
  `is_delete` enum('0','1') NOT NULL DEFAULT '0',
  `added_date` datetime NOT NULL,
  `updated_date` datetime NOT NULL,
  `remark` text NOT NULL,
  PRIMARY KEY (`a_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 4: Now need to post the form and recieve data and show errors, Recieve post Before the HTML form

if(isset($_POST['is_post'])) //check form is posted
{
	extract($_POST);//extract the form in its filed name vars using php function extract
	
	
	//now create a is_unique rule for ad name for AD/EDIT MOde both 
	
	if(isset($edit_id) && $edit_id!=0)//it means it is in edit mode
	{
		$is_unique_expression="tbl_ads::ad_name::a_id!=".$edit_id;
	}
	else
	{
		$is_unique_expression="tbl_ads::ad_name";
	}
	
	/*
	So for -> is_unique_expression :: First data is for `table_name`
	second is for `column_name` to match
	third is for `where_condition` in edit case or any specific requirement (optional)
	ALl are seperated with :: (double colon)
	*/
	 
	
		//validation rules 
		
		$config_validation=array(
		array('field'=>"ad_name",
		"label"=>"Ad Campaign Name",
		"rules"=>"required|is_unique[".$is_unique_expression."]",
		),
		array('field'=>"campaign_type",
		"label"=>"Campaign Type",
		"rules"=>"required",
		),
		array('field'=>"is_active",
		"label"=>"Ad Campaign Status",
		"rules"=>"required",
		),
		array('field'=>"ad_media_file",
		"label"=>"Creative Banner",
		"rules"=>"file_required|valid_file[AD_MEDIA::png,jpg,jpeg,gif]",
		),
		array('field'=>"end_url",
		"label"=>"Target Url",
		"rules"=>"required|valid_url",
		)
		);
		
		//rule names must seperated with pipe |
		/*
		rule      =>    usage
		required  =>  means must required item
		valid_url =>   used for validate a url format
		file_required => user to set must upload validation for a input type file
		valid_file => valid file passes a string for validate file time in []
		              fist is the folder name seperated with double column :: second is 
					  for extnsions seperated with comma (,)
		is_unique => used for matching value already exist in database or not for 
					both  edit and add case, in edit case we can pass the extra where case
					for self safe 
		
		
		*/
	
	
	//now pass the configuration array of fileds
	$validation->init($config_validation);
	
	
	//if form successfully submitted by passing all rules//
	if($validation->form_success==1)
	{
		
		//do whatever want to do
		if(isset($edit_id) && $edit_id!=0) //detect it is in edit mode
		{
			$ad_media_file = (isset($validation->return_array['ad_media_file']))?$validation->return_array['ad_media_file']:"";
			
			//$validation->return_array is a array set the key with file field name if file successfully posted.
			//means it set the file field name key in '$validation->return_array' with input type file name.
			//so we can get the uploaded file name by passing the file type field name in $validation->return_array like this >> $validation->return_array['ad_media_file'];
			
			
			//this is save action when we edit any item
			$date=date('Y-m-d H:i:s');
			
			$update = array(
				'ad_name' => $ad_name,
				'is_active' => $is_active,
				'dimension' => $dimension,
				'end_url' => $end_url,
				'updated_date' => $date
			);
			if($ad_media_file!="")
			{
				$update['ad_media_file'] = $ad_media_file;
			}
			//Add the WHERE clauses
			$where_clause = array(
				'a_id' => $edit_id
			);
			$updated = $database->update( 'tbl_ads', $update, $where_clause, 1 );
			if( $updated )
			{
				header('location:campaign.php?msg=Ad Campaign Updated Successfully!');
			}
		}
		else
		{ //detect that form post done for add a new campaign
			$ad_media_file = $validation->return_array['ad_media_file'];
	
			//this is add action where we add new item
			$date=date('Y-m-d H:i:s');
			$data = array(
				'ad_name' => $ad_name,
				'campaign_type' => $campaign_type,
				'user_id' => $_SESSION['user_id'],
				'is_active' => $is_active,
				'dimension' => $dimension,
				'ad_media_file' => $ad_media_file,
				'end_url' => $end_url,
				'added_date' => $date,
				'updated_date' => $date
				
			);
			
			$add_query = $database->insert( 'tbl_ads', $data );
			if( $add_query )
			{
				header('location:campaign.php?msg=Ad Campaign Added Successfully!');
			}
		}
		//do whatever want to do
	}
	else{
		
		//echo "<pre>";
		//print_r($validation->errors_array);
		//die;
		
		//$validation->errors_array is the complete array with all errors of form.
	}

	
}

Please Comment If any problem in this. I’ll assist you to use this form validation library