[PHP] Validation

Validation is headache. Fortunately, this function makes it better. Sample usage is as follows:


function fields_validation($field){
	$validation_rules = array();
	if(isset($field->slug)){
		$slug = $field->slug;
	} else {
		$slug = sanitize_title($field->label);
	}
	$label = $field->label;
	if(intval($field->minLength) != '0'){
		$minLength = intval($field->minLength);
		$validation_rules[] = "length>=$minLength,$slug,$label must be at least $minLength characters long.";
	}
	if(intval($field->maxLength) != '0'){
		$maxLength = intval($field->maxLength);
		$validation_rules[] = "length<=$maxLength,$slug,$label must be $maxLength characters long maximum.";
	}				
	if($field->isEmail){
		$validation_rules[] = "valid_email,$slug,Please enter a valid email address.";
	}
	return $validation_rules;
}

and then call the function itself

$validation_rules = fields_validation($field);
$errors = validateFields($_POST, $validation_rules);

$errors will be an array. A simple !empty($errors) will check for errors.

The conditions represents the rule that must be true in order not to produce an error. For example, length <= $maxLength means that the length must be less than max length to pass the check. $slug is the name of the form’s field.

2 thoughts on “[PHP] Validation

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>