Location: PHPKode > scripts > Combo Validation > combo-validation/examples/customValidation.php
<?php
/**
* @package ComboValidation
* @subpackage Examples
*/
require_once('includes.inc.php');
#--(Begin)-->Validation
/**
* @notice all of the options and suboption names are case insensitive
*/
$validation=cmfcValidation::factory('v1',array(
	'formName'=>'myForm',
	'fieldTypesInfo'=>array(
		'age'=>array(
			'validationHandler'=>array(
				'function'=>'validateAge' //name of the function or array of the object method array(&obj,'methodName')
			),
			'jsValidationHandler'=>array(
				'function'=>'validateAge' //name of the function or array of the object method array(&obj,'methodName')
			)
		)
	),
	'fieldsInfo'=>array(
		"contactInfo[name]"=>array(
			'title'=>'Name',
			'type'=>'string',
			'param'=>array(
				'notEmpty'=>true
			)
		),
		"contactInfo[email]"=>array(
			'title'=>'Email',
			'type'=>'email',
			'param'=>array(
			)
		),
		"contactInfo[subject]"=>array(
			'title'=>'Subject',
			'type'=>'string',
			'param'=>array(
				'notEmpty'=>true,
				'lengthMin'=>10,
				'lengthMax'=>100,
				'regexp'=>'/agreed/i',//php regex with preg_match
				'jsRegexp'=>'/agreed/i',//javascript regex with preg_match
				'regexpDescription'=>' : should contains "agreed" word'
			)
		),
		"contactInfo[description]"=>array(
			'title'=>'Description',
			'type'=>'string',
			'param'=>array(
				'notEmpty'=>true
			)
		),
		"contactInfo[tel]"=>array(
			'title'=>'Tel',
			'validationHandler'=>array(
				'function'=>'validateEmailTelRelation', //name of the function or array of the object method array(&obj,'methodName')
				'parameters'=>array() //if your function has additional parameters
			),
			'type'=>'number',
			'param'=>array(
				'countMin'=>5,
				'countMax'=>7
			)
		),
		"contactInfo[age]"=>array(
			'title'=>'Age',
			'type'=>'age',
			'likeType'=>'number',
			'param'=>array(
				'notEmpty'=>true,
				'countMin'=>2, //min number of characters
				'countMax'=>3, //max number of characters
				'min'=>18, //min value
				'max'=>110 //max value
			)
		),
		"contactInfo[website]"=>array(
			'title'=>'Website',
			'type'=>'url',
			'param'=>array(
			)
		),
		"contactInfo[subscription]"=>array(
			'title'=>'Subscription',
			'type'=>'checkBox',
			'param'=>array(
				'notEmpty'=>true
			)
		)
		
	)
));

/**
* overriding the options is possible via following code
*/
//$validation->setOption('optionName','optionValue');
/**
* for multilingual website you can change this messages easily
* @notice do not include following code into class initializing array, because messages name (definitions)
* 			define after object initializing
*/
$validation->setOption('messagesValue',array(
	CMF_ValidationV1_Error=>'Unknown error',
	CMF_ValidationV1_Is_Not_Valid_Email=>'"__value__" in __title__ is not valid email',
	CMF_ValidationV1_Is_Not_Valid_Url=>'"__value__" in __title__ is not valid url',
	CMF_ValidationV1_Is_Not_Number=>'"__value__" in __title__ is not number',
	CMF_ValidationV1_Is_Not_Within_Range=>'"__value__" of __title__ is not within this range (__min__,__max__)',
	CMF_ValidationV1_Is_Not_Within_Count_Range=>'"__value__" of __title__ is not within this count range (__min__,__max__)',
	CMF_ValidationV1_Is_Empty=>'__title__ value should not be empty',
	CMF_ValidationV1_Is_Not_Selected=>'__title__ is not selected',
	CMF_ValidationV1_Is_Not_Within_Length_Range=>'"__value__" of __title__ is not within this length range (__min__,__max__)',
	CMF_ValidationV1_Is_Not_String=>'__title__ is not string',
	CMF_ValidationV1_Is_Not_Match_With_Pattern=>'__title__ is not match with __desc__',
	CMF_ValidationV1_Field_Does_No_Exists=>'__title__ field "__fieldName__" does not exists'
));

function validateAge($validation,$fieldsValues,$fieldInfo,$patternName) {
	$fieldValue=$fieldsValues[$fieldInfo['headName']];
	$isValid=false;
	if (is_numeric($fieldValue))
		if ($fieldValue>=1 and $fieldValue<=100)
			$isValid=true;
	if (!$isValid)
		return $validation->raiseError('Age should be number and between 1-100' ,'', PEAR_ERROR_RETURN, NULL, array('title'=>$fieldInfo['title'],'value'=>$fieldValue));
}


//custom validation: validateBefore,validate,validateAfter
$validation->prependCommandHandler('validateAfter','customValidate');
function customValidate($validation,$cmd,$params) {
	$fieldsValues=$params['fieldsValues'];
	$patternName=$params['patternName'];
	$fieldInfo=$validation->getOption('fieldsInfo');

	$result=array();
	if (empty($fieldsValues['email']) and empty($fieldsValues['tel']))
		$result[]=$validation->raiseError('One of the fields "Tel" or "Email" should be filled' ,'', PEAR_ERROR_RETURN, NULL, array('title'=>$fieldInfo['title'],'value'=>$fieldValue));
    
    return $result;
}
#--(End)-->Validation


$successfulSubmit = 0;
$messages='';
if (isset($_POST['submit_send'])){

	/**
	* validating form via package
	*/
	$validateResult=$validation->validate($_POST);
	
	if (empty($validateResult)) {
		$messages[]='Bingo!';
	} else {
		foreach ($validateResult as $r){
			$messages[]=$r->getMessage();
			$successfulSubmit = 0;
		}		
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<title>Custom Validation Example</title>
</head>
<body>
	<a href="index.php">Home</a>
	<p>
	- You can define new field type or override predefined field types, and validate field with this new type.
	In This example new field type called age is added.(age is number and is between 1-100)
	</p>
	<p>
	- It's also possible to extend the class validation method with your function,
	so you can even validate related fields. in this example one of the fields "Tel" or "Email"
	should be filled.
	</p>
	<p>
	- via custom validation function, you can also combine combo validation with Ajax!
	</p>
	<?php

	?>
	<table width="541" border="0" cellspacing="0" cellpadding="0">
		<tr>
			<td class="boxbody" >
				<? if (is_array($messages)) { ?>
				<div align="center">
					<div align="left" style="color:red;padding:3px">
						<?
						foreach($messages as $message){
							echo $message."<br/>";
						}
						?>
					</div>
				</div>
				<? }?>
				
				<div style="margin:5px; text-align:justify">
				</div>
					
				<br />
	
			<? if (!$successfulSubmit) { 
					/**
					* print requrie javascript codes for validating form via javascript
					* if you only need php validation, you can comment following 2 line codes
					*/
					$validation->printJsClass();
					$validation->printJsInstance();
			?>
			
				<script>
					/**
					* function for validating new field type
					*/
					function validateAge(validation,fieldInfo,fieldValue) {
						if (fieldValue>=1 && fieldValue<=100)
							return '';
						else
							return validation.raiseError('__title__ should be number and between 1-100','','ERROR_RETURN',null, {'title':fieldInfo['title']} );
					}
					/**
					* custom javascript validation function
					*/
					function validateAfter(_this,cmd,params) {
						var fieldsInfo=params['fieldsInfo'];
						var fieldObj;
						
						fieldObj=_this.getFormFieldObject(fieldsInfo['contactInfo[email]']['name'],_this.formObj);
						fieldsInfo['contactInfo[email]']['value']=fieldObj.value;
						
						fieldObj=_this.getFormFieldObject(fieldsInfo['contactInfo[tel]']['name'],_this.formObj);
						fieldsInfo['contactInfo[tel]']['value']=fieldObj.value;
						
						if (_this.isEmpty(fieldsInfo['contactInfo[email]']['value']) && _this.isEmpty(fieldsInfo['contactInfo[tel]']['value']))
							return ['One of the fields "Tel" or "Email" should be filled'];

						return [''];
					}
				
					<?php
					/**
					* assign javascript function for handling validation after main validation.
					* generated messages will merge with previous messages
					*/
					$validation->jsfAddCommandHandler('validateBefore','validateAfter');echo ';';
					?>
				</script>
				
				<form name="myForm" action="?<?=cmfcUrl::excludeQueryStringVars(array('pt', 'pageType', 'sectionName'),'get') ?>" method="post" enctype="application/x-www-form-urlencoded">
					<table width="100%" border="0" cellspacing="5" cellpadding="0" style="text-align:<?= $align ?>; direction:<?= $dir ?>">
						<tr>
							<td>Name : </td>
							<td><input class="input" name="contactInfo[name]" value="<?=$_POST['contactInfo']['name']?>" type="text" /></td>
						</tr>	
						<tr>
							<td>Tel : </td>
							<td><input class="input" name="contactInfo[tel]" value="<?=$_POST['contactInfo']['tel']?>" type="text" style="direction:ltr" /></td>
						</tr>
						<tr>
							<td>Age : </td>
							<td><input class="input" name="contactInfo[age]" value="<?=$_POST['contactInfo']['age']?>" type="text" style="direction:ltr" /></td>
						</tr>
						<tr>
							<td>Email : </td>
							<td><input class="input" name="contactInfo[email]" value="<?=$_POST['contactInfo']['email']?>" type="text" /></td>
						</tr>
						<tr>
							<td>Website : </td>
							<td><input class="input" name="contactInfo[website]" value="<?=$_POST['contactInfo']['website']?>" type="text" /></td>
						</tr>
						<tr>
							<td>Subject : </td>
							<td><input class="input" name="contactInfo[subject]" value="<?=$_POST['contactInfo']['subject']?>" type="text"  /></td>
						</tr>
						<tr>
							<td>Description : </td>
							<td><textarea class="textarea" name="contactInfo[description]" cols="40" rows="4" ><?=$_POST['contactInfo']['description']?></textarea></td>
						</tr>
						<tr>
							<td>Subscription : </td>
							<td><input class="input" name="contactInfo[subscription]" value="1" <?=($_POST['contactInfo']['subscription']==1)?'checked':''?> type="checkbox"  /></td>
						</tr>
						<tr>
							<td></td>
							<td><input class="button" name="submit_send" type="submit" value=" Send " /></td>
						</tr>
					</table>
				</form>
			<? } ?>
			</td>
		</tr>
	</table>
</body>
</html>
Return current item: Combo Validation