2016-03-17 52 views
1

感謝這個論壇,我碰到下面的form validator某些時候返回哪個工作正常。但是,我只有一個問題。Formvalidator檢查即使值爲空

當提交一個空的textarea的表單時,它會返回空字段作爲錯誤。但是,由於價值不是強制性的,我需要以某種方式糾正這一點。

<?php 
/** 
* Pork Formvalidator. validates fields by regexes and can sanatize them.   Uses PHP  filter_var built-in functions and extra regexes 
* @package pork 
*/ 


/** 
* Pork.FormValidator 
* Validates arrays or properties by setting up simple arrays 
* 
* @package pork 
* @author SchizoDuckie 
* @copyright SchizoDuckie 2009 
* @version 1.0 
* @access public 
*/ 
class FormValidator 
{ 
public static $regexes = Array(
     'date' => "^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}\$", 
     'datetime' => "20\d{2}(-|\/)((0[1-9])|(1[0-2]))(-|\/)((0[1-9])|([1-2][0-9])|(3[0-1]))(T|\s)(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])", 
     'amount' => "^[-]?[0-9]+\$", 
     'number' => "^[-]?[0-9,]+\$", 
     'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$", 
     'not_empty' => "[a-z0-9A-Z]+", 
     'words' => "^[A-Za-z]+[A-Za-z \\s]*\$", 
     'phone' => "^[0-9]{10,11}\$", 
     'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$", 
     'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$", 
     'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$", 
     '2digitopt' => "^\d+(\,\d{2})?\$", 
     '2digitforce' => "^\d+\,\d\d\$", 
     'anything' => "^[\d\D]{1,}\$", 
     'username' => "^[\w]{3,32}\$" 
); 

private $validations, $sanatations, $mandatories, $equal, $errors, $corrects, $fields; 


public function __construct($validations=array(), $mandatories = array(), $sanatations = array(), $equal=array()) 
{ 
$this->validations = $validations; 
$this->sanatations = $sanatations; 
$this->mandatories = $mandatories; 
$this->equal = $equal; 
$this->errors = array(); 
$this->corrects = array(); 
} 

/** 
* Validates an array of items (if needed) and returns true or false 
* 
* JP modofied this function so that it checks fields even if they are not submitted. 
* for example the original code did not check for a mandatory field if it was not submitted. 
* Also the types of non mandatory fields were not checked. 
*/ 
public function validate($items) 
{ 
$this->fields = $items; 
$havefailures = false; 

//Check for mandatories 
foreach($this->mandatories as $key=>$val) 
{ 
    if(!array_key_exists($val,$items)) 
    { 
     $havefailures = true; 
     $this->addError($val); 
    } 
} 

//Check for equal fields 
foreach($this->equal as $key=>$val) 
{ 
    //check that the equals field exists 
    if(!array_key_exists($key,$items)) 
    { 
     $havefailures = true; 
     $this->addError($val); 
    } 

    //check that the field it's supposed to equal exists 
    if(!array_key_exists($val,$items)) 
    { 
     $havefailures = true; 
     $this->addError($val); 
    } 

    //Check that the two fields are equal 
    if($items[$key] != $items[$val]) 
    { 
     $havefailures = true; 
     $this->addError($key); 
    } 
} 

foreach($this->validations as $key=>$val) 
{ 
     //An empty value or one that is not in the list of validations or one that is not in our list of mandatories 
     if(!array_key_exists($key,$items)) 
     { 
       $this->addError($key, $val); 
       continue; 
     } 

     $result = self::validateItem($items[$key], $val); 

     if($result === false) { 
       $havefailures = true; 
       $this->addError($key, $val); 
     } 
     else 
     { 
       $this->corrects[] = $key; 
     } 
} 

return(!$havefailures); 
} 

/* JP 
* Returns a JSON encoded array containing the names of fields with errors and those without. 
*/ 
public function getJSON() { 

$errors = array(); 

$correct = array(); 

if(!empty($this->errors)) 
{    
    foreach($this->errors as $key=>$val) { $errors[$key] = $val; }    
} 

if(!empty($this->corrects)) 
{ 
    foreach($this->corrects as $key=>$val) { $correct[$key] = $val; }     
} 

$output = array('errors' => $errors, 'correct' => $correct); 

return json_encode($output); 
} 



/** 
* 
* Sanatizes an array of items according to the $this->sanatations 
* sanatations will be standard of type string, but can also be specified. 
* For ease of use, this syntax is accepted: 
* $sanatations = array('fieldname', 'otherfieldname'=>'float'); 
*/ 
public function sanatize($items) 
{ 
foreach($items as $key=>$val) 
{ 
     if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue; 
     $items[$key] = self::sanatizeItem($val, $this->validations[$key]); 
} 
return($items); 
} 


/** 
* 
* Adds an error to the errors array. 
*/ 
private function addError($field, $type='string') 
{ 
$this->errors[$field] = $type; 
} 

/** 
* 
* Sanatize a single var according to $type. 
* Allows for static calling to allow simple sanatization 
*/ 
public static function sanatizeItem($var, $type) 
{ 
$flags = NULL; 
switch($type) 
{ 
     case 'url': 
       $filter = FILTER_SANITIZE_URL; 
     break; 
     case 'int': 
       $filter = FILTER_SANITIZE_NUMBER_INT; 
     break; 
     case 'float': 
       $filter = FILTER_SANITIZE_NUMBER_FLOAT; 
       $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND; 
     break; 
     case 'email': 
       $var = substr($var, 0, 254); 
       $filter = FILTER_SANITIZE_EMAIL; 
     break; 
     case 'string': 
     default: 
       $filter = FILTER_SANITIZE_STRING; 
       $flags = FILTER_FLAG_NO_ENCODE_QUOTES; 
     break; 

} 
$output = filter_var($var, $filter, $flags);    
return($output); 
} 

/** 
* 
* Validates a single var according to $type. 
* Allows for static calling to allow simple validation. 
* 
*/ 
public static function validateItem($var, $type) 
{ 
if(array_key_exists($type, self::$regexes)) 
{ 
     $returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false; 
     return($returnval); 
} 
$filter = false; 
switch($type) 
{ 
     case 'email': 
       $var = substr($var, 0, 254); 
       $filter = FILTER_VALIDATE_EMAIL;   
     break; 
     case 'int': 
       $filter = FILTER_VALIDATE_INT; 
     break; 
     case 'boolean': 
       $filter = FILTER_VALIDATE_BOOLEAN; 
     break; 
     case 'ip': 
       $filter = FILTER_VALIDATE_IP; 
     break; 
     case 'url': 
       $filter = FILTER_VALIDATE_URL; 
     break; 
} 
return ($filter === false) ? false : filter_var($var, $filter) !== false ? true :  false; 
}   
} 
?> 

所以從我的理解,我需要拿出一種方法來驗證空字符串,因爲上面的代碼會拋出一個錯誤。

$validations = array(
    'id' => 'number', //Value in _POST['id'] = '11' 
    'time' => 'datetime', //Value in _POST['time'] = '2016-03-17T11:05:01' 
    'description' => 'anything'); //Value in _POST['decription'] = '' 

$required = array('id', 'time'); 

$validator = new FormValidator($validations, $required); 

$validator->validate($_POST); 
print_r $validator->getJSON(); 
+1

'filter_var($ VAR,$過濾器)!==假的? true:false' =>我愛你的風格:) –

+0

@Thomas:至少,它是'true' :-) – Jan

回答

0

您應該使所需的字段並添加像這樣

// validation 
    if (empty($variable)) { 
     echo 'such&such is required<br />'; 
     $ok = false; 
    } 

,或使變量=""null;

+0

添加了這個,仍然是相同的錯誤:''description'=> strlen($ _ POST [「description」]) ? '':$ _POST [「action_description」],'如果我使用'empty',則相同 – Andy

+0

您確定您的輸入表單正確嗎? –

+0

是的,當將一個值設置爲'description'時,它們沒有錯誤。但是,如果在'textarea'中沒有設置任何值,即使我使用''description'=> empty($ _ POST [「description」]),也會引發錯誤。 '':$ _POST [「action_description」],' – Andy