<?php
/* Cleans and validates (form) entries
 * HOW TO USE
 * Call a validation method and examine the returned value, R. If(R!=$this->invalid) then validation passed.
*/

class validator {
	public $invalid = "-1-1#$%_not_valid"; //the value to return if invalid
	
	/* The possible validation type strings used in validation */
	public $vb_email = "email";
	public $vb_fullname = "fullname";
	public $vb_normal = "normal";
	public $vb_isdigits = "digits";
	
    function __construct(){}
    
	/* General Validation
	 * $str - the string to validate
	 * $vtype - the type of validation required
	 * Returns the $invalid class member if validation fails or the 'cleaned' version of the supplied $str param if validation succeeds 
	*/
	function validate($str, $vtype = "normal"){ //vtype - the type of validation required
		$str = mysql_real_escape_string(strip_tags(trim($str)));
		$ret = $str;
		
		switch($vtype){
			case $this->vb_email:
			if(!filter_var($str, FILTER_VALIDATE_EMAIL)) $ret = $this->invalid;
			break;
			
			case $this->vb_fullname: //assumes a fullname or data of such sort cannot be less than 2 chars long
			if(strlen($str)<2) $ret = $this->invalid;
			break;
			
			case $this->vb_isdigits:
			if(!ctype_digit($str)) $ret = $this->invalid;
			break;
			
			default: 
			break;
		}
		return $ret;
	}
	/* Number Range Validation
	 * Checks if number ($num) is in valid range (between $ptA and $ptB).
	 * Returns the $invalid class member if validation fails or the string version of the supplied $num param if validation succeeds 
	*/
	function int_range_validate($num, $ptA, $ptB){
		$num = $num.""; //make sure it's a string so it can be trimed ...
		$num = strip_tags(trim($num));
		$ret = $num;
		if(!ctype_digit($num)){
			$ret = $this->invalid;
		}else{
			$num = (int) $num;
			if(!($ptA <= $num && $ptB >= $num)) $ret = $this->invalid;
		}
		return $ret;
	}
}
?>