2009-04-10 15 views
30

मुझे एक साधारण PHP लाइब्रेरी की आवश्यकता है जिसका उपयोग नियमों और फ़ील्ड नामों को आसानी से पास करने के लिए किया जा सकता है, और फिर सत्यापन आसानी से किया जा सकता है। त्रुटियों को पुनर्प्राप्त करने का एक आसान तरीका भी होना चाहिए।सबसे आसान फॉर्म सत्यापन पुस्तकालय?

कोई सुझाव?

उत्तर

61

मैंने अपने स्वयं के एक साधारण वर्ग को लिखा, मैंने पिछले कुछ वर्षों में PHP के sanatize और फ़िल्टर फ़ंक्शंस के साथ एकत्र किए गए कुछ regexes को जोड़ दिया।

<? 
/** 
* 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}\$", 
      '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,}\$" 
    ); 
    private $validations, $sanatations, $mandatories, $errors, $corrects, $fields; 


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

    /** 
    * Validates an array of items (if needed) and returns true or false 
    * 
    */ 
    public function validate($items) 
    { 
     $this->fields = $items; 
     $havefailures = false; 
     foreach($items as $key=>$val) 
     { 
      if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) 
      { 
       $this->corrects[] = $key; 
       continue; 
      } 
      $result = self::validateItem($val, $this->validations[$key]); 
      if($result === false) { 
       $havefailures = true; 
       $this->addError($key, $this->validations[$key]); 
      } 
      else 
      { 
       $this->corrects[] = $key; 
      } 
     } 

     return(!$havefailures); 
    } 

    /** 
    * 
    * Adds unvalidated class to thos elements that are not validated. Removes them from classes that are. 
    */ 
    public function getScript() { 
     if(!empty($this->errors)) 
     { 
      $errors = array(); 
      foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; } 

      $output = '$$('.implode(',', $errors).').addClass("unvalidated");'; 
      $output .= "alert('there are errors in the form');"; // or your nice validation here 
     } 
     if(!empty($this->corrects)) 
     { 
      $corrects = array(); 
      foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; } 
      $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");'; 
     } 
     $output = "<script type='text/javascript'>{$output} </script>"; 
     return($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; 
    }  



} 

अब इस जावास्क्रिप्ट आप यहाँ देख से कुछ के लिए mootools की आवश्यकता है, लेकिन आप आसानी से अपने पसंदीदा जावास्क्रिप्ट ढांचे के लिए बदल सकते हैं। यह सब तत्व को देखता है, और 'अनधिकृत' सीएसएस वर्ग को इसमें जोड़ता है।

प्रयोग के रूप में सरल है के रूप में मैं हमेशा कभी चाहता था:

उदाहरण:

$validations = array(
    'name' => 'anything', 
    'email' => 'email', 
    'alias' => 'anything', 
    'pwd'=>'anything', 
    'gsm' => 'phone', 
    'birthdate' => 'date'); 
$required = array('name', 'email', 'alias', 'pwd'); 
$sanatize = array('alias'); 

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

if($validator->validate($_POST)) 
{ 
    $_POST = $validator->sanatize($_POST); 
    // now do your saving, $_POST has been sanatized. 
    die($validator->getScript()."<script type='text/javascript'>alert('saved changes');</script>"); 
} 
else 
{ 
    die($validator->getScript()); 
} 

सिर्फ एक तत्व को मान्य करने के लिए:

$sanatized = new FormValidator()->sanatize('<b>blah</b>', 'string'); 
:

$validated = new FormValidator()->validate('[email protected]', 'email'); 

सिर्फ एक तत्व sanatize करने के लिए

टी इस कक्षा के बारे में वह सबसे अच्छी बात यह है कि आप अपने फॉर्म को AJAX या iframe लक्ष्य के साथ भेज सकते हैं और परिणामस्वरूप स्क्रिप्ट निष्पादित कर सकते हैं। पृष्ठ को रीफ्रेश करने या ब्राउज़र पर उसी फ़ॉर्म डेटा को फिर से भेजने की आवश्यकता नहीं है :) इसके अलावा, यदि स्क्रिप्ट को बदलने की आवश्यकता है, तो विश्लेषण करने के लिए कोई मुश्किल ओवरडिज़ाइन फ्रेमवर्क नहीं है, बस इसे किसी भी तरह से बदलें :)

ओह हाँ, इसे कहीं भी इस्तेमाल करने के लिए स्वतंत्र महसूस करें। कोई भी लाइसेंस

+3

ध्यान दें कि यह पीएचपी संस्करणों पर काम नहीं करेगा 5.2 से पहले क्योंकि आप filter_var – Ray

+0

का उपयोग कर रहे हैं, मुझे लगता है कि आपको 'array_search ($ key, $ this-> सत्यापन) 'array_key_exists ($ key, $ this-> सत्यापन)' को प्रतिस्थापित करना चाहिए। क्या यह सही है? – UnLoCo

+0

विस्मयकारी कक्षा दोस्त! –

12

यदि आप अपने आप को कुछ प्रोग्राम करना चाहते हैं और आपके पास PHP 5.2.0 या उच्चतर है। तो फिर तुम filter functions.

2

आप नामित सिम्फोनी ढांचा का एक हिस्सा सिम्फोनी रूपों, जो पूरी ढांचे के अलावा इस्तेमाल किया जा सकता है इस पर गौर कर सकते हैं।

the framework documentation पर एक नज़र डालें।

4

है एक कोड आग लगनेवाला ढांचे में शामिल है, here

मैं PHP चौखटे में से एक का उपयोग शुरू करने की सलाह देते हैं एक नजर है;)

5

Zend Forms जो पूरे Zend फ्रेमवर्क के बिना इस्तेमाल किया जा सकता

23

SchizoDuckie से जवाब ऊपर भयानक था। मैंने प्रोजेक्ट में अपना कोड इस्तेमाल किया है, मैं लेखक की अनुमति के साथ काम कर रहा हूं। इस कोड का उपयोग करने वाला एक मुद्दा यह था कि यदि एक आवश्यक फ़ील्ड सबमिट नहीं किया गया था तो यह एक त्रुटि पंजीकृत नहीं करेगा। मैंने इस परिदृश्य को कवर करने के लिए कोड को संशोधित किया है। मैंने एचटीएमएल और जावास्क्रिप्ट उत्पन्न करने के लिए कोड भी हटा दिया है क्योंकि मेरी परियोजना यूआई के तर्क को प्रति एमवीसी पैटर्न से अलग करने की मांग करती है। संशोधित कोड बस JSON एन्कोडेड परिणाम देता है। यदि मैं दूसरों के लिए कुछ उपयोग करता हूं तो मैं यहां संशोधित कोड को दोबारा पोस्ट करता हूं।

<? 
/** 
* 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}\$", 
      '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; 
}   
} 
?> 
0

यह phpro.org सत्यापन वर्ग आसान डेटा सत्यापन के लिए बहुत अच्छा लग रहा है:

http://www.phpro.org/classes/Validation-Class.html

यह लंबाई की तरह नियमों का समर्थन करता है, आदि

संबंधित मुद्दे