tp自動驗證功能

protected $_validate=array(
			array('goods_name','require','商品名不能爲空','require'),
			array('cat_id','value','分類名只能爲整數','number'),
			array('goods_number','field','庫存名只能爲整數','number'),
			array('goods_price','field','商品價只能爲整數','number'),
			array('is_hot','value','數值只能在0和1之間','in','0,1'),
			array('is_new','value','數值只能在0和1之間','in','0,1')						
	);

public function Vadidata($data){
  	  
  	  if (!empty($this->_validate)) {
  	  	  foreach ($this->_validate as $val){
  	  	  	
  	  	  	  switch ($val[1]){
  	  	  	  	case 'require':  //必須驗證的字段  	  	  	  		
  	  	  	       if(false===$this->VadidateField($data, $val)){
  	  	  	       	
  	  	  	  				$this->error=$val[2];
  	  	  	  				return false;
  	  	  	  			}
  	  	  	  		break;
  	  	  	  	case 'value': //有該值就驗證
  	  	  	  		if (''!=trim($data[$val[0]])) {
  	  	  	  		   if(false===$this->VadidateField($data, $val)){
  	  	  	  				$this->error=$val[2];
  	  	  	  				return false;
  	  	  	  			}
  	  	  	  		}
  	  	  	  		break;
  	  	  	  	case 'field':   //有該字段就驗證
  	  	  	  		if (!empty($data[$val[0]])) {
  	  	  	  			if(false===$this->VadidateField($data, $val)){
  	  	  	  				$this->error=$val[2];
  	  	  	  				return false;
  	  	  	  			}
  	  	  	  		}
  	  	  	  		break;  	  	  	  				
  	  	  	  }
  	  	  }
  	  }
  	 return true; 
  }
  
  
  protected function VadidateField($data,$val){
  	   switch ($val[3]){
  	   	
  	   	case 'require':
  	   		return !empty($data[$val[0]]);
  	   	case 'in':  	   		
  	   	case 'between':
  	   		$parm=explode(',', $val[4]);
  	   		$min=min($parm);$max=max($parm);
  	   		if ($val[3]=='in') {
  	   			return in_array($data[$val[0]], $parm);
  	   		}
  	   		if ($val[3]=='between') {
  	   			return $data[$val[0]]>$min && $data[$val[0]]<$max;
  	   		}
  	   	case 'number':
  	   		return is_numeric($data[$val[0]]);	 	   					
  	      }
  	     
  }
相關文章
相關標籤/搜索