Friday, December 11, 2009

Validate a text


In this example, we implement text validation. Validators are chained together. We also implement custom validations.

Components used in this example
Implementation of the validation process
  • We define the list of Zend validators. We exclude some validators where parameters are needed. We also exclude the validators for databases.
  • We define the list of custom validators.
  • We define hard coded values for some numeric validators.
  • We define hard coded values for the validators for files.

class MyValidate
{
    
// We define the list of Zend validators.
    // We exclude some validators where parameters are needed.
    // We also exclude the validators for databases.
    
public $zendValidators = array(
        
'Zend_Validate_Alnum',
        
'Zend_Validate_Alpha',
        
// 'Zend_Validate_Barcode',
        
'Zend_Validate_Barcode_Ean13',
        
'Zend_Validate_Barcode_UpcA',
        
'Zend_Validate_Between',
        
'Zend_Validate_Ccnum',
        
'Zend_Validate_Date',
        
// 'Zend_Validate_Db_NoRecordExists',
        // 'Zend_Validate_Db_RecordExists',
        
'Zend_Validate_Digits',
        
'Zend_Validate_EmailAddress',
        
// 'Zend_Validate_File_Count',
        
'Zend_Validate_File_Crc32',
        
// 'Zend_Validate_File_ExcludeExtension',
        // 'Zend_Validate_File_ExcludeMimeType',
        // 'Zend_Validate_File_Exists',
        
'Zend_Validate_File_Extension',
        
'Zend_Validate_File_FilesSize',
        
// 'Zend_Validate_File_Hash',
        // 'Zend_Validate_File_ImageSize',
        // 'Zend_Validate_File_IsCompressed',
        // 'Zend_Validate_File_IsImage',
        
'Zend_Validate_File_Md5',
        
// 'Zend_Validate_File_MimeType',
        // 'Zend_Validate_File_NotExists',
        
'Zend_Validate_File_Sha1',
        
'Zend_Validate_File_Size',
        
// 'Zend_Validate_File_Upload',
        
'Zend_Validate_File_WordCount',
        
'Zend_Validate_Float',
        
'Zend_Validate_GreaterThan',
        
'Zend_Validate_Hex',
        
'Zend_Validate_Hostname',
        
'Zend_Validate_Iban',
        
'Zend_Validate_Identical',
        
// 'Zend_Validate_InArray',
        
'Zend_Validate_Int',
        
'Zend_Validate_Ip',
        
'Zend_Validate_LessThan',
        
'Zend_Validate_NotEmpty',
        
// 'Zend_Validate_Regex',
        // 'Zend_Validate_Sitemap_Changefreq',
        // 'Zend_Validate_Sitemap_Lastmod',
        // 'Zend_Validate_Sitemap_Loc',
        // 'Zend_Validate_Sitemap_Priority',
        // 'Zend_Validate_StringLength',
    
);

    
// We define the list of custom validators.
    
public $customValidators = array(
        
'MyLowerCaseValidator',
        
'MyUpperCaseValidator',
    );

    public 
$min;
    public 
$max;
    public 
$crc32;
    public 
$extension;
    public 
$size;
    public 
$md5;
    public 
$sha1;
    public 
$wordCount;
    public 
$identical;

    public function 
__construct()
    {
        
// We define hard coded values for some numeric validators.
        
$this->min 10;
        
$this->max 20;

        
// We define hard coded values for the validators for files.
        
$this->crc32 hash_file('CRC32'__FILE__);
        
$info pathinfo(__FILE__);
        
$this->extension $info['extension'];
        
$this->size filesize(__FILE__);
        
$this->md5 hash_file('MD5'__FILE__);
        
$this->sha1 hash_file('SHA1'__FILE__);
        
$this->wordCount str_word_count(file_get_contents(__FILE__));
        
$this->identical 'identical';
    }
Text validation
  • We get the text and the validators, from the GET request.
  • We instantiate the validator chain.
  • If the validator is a numeric validator, we instantiate the validator with one or more target values.
  • If the validator is a validator for files, we instantiate the validator and we use this file as a target.
  • We update the template of the error message for the file size, because we only validate for the exact size.
  • And we perform the validation.
  • If this is another validator, we simply add the validator.
  • And we perform the validation if it has not been done yet.
  • We return the error message if the validation failed.
  • If we catch an exception, we return the error message.

    public function process()
    {
        
// We get the text and the validators, from the GET request.
        
list($data$validators) = $this->_getParameters();

        try {
            if (empty(
$validators)) {
                
$result 'Please enter some text and select one or more validators!';
            } else {
                
// We instantiate the validator chain.
                
$validatorChain = new Zend_Validate();

                foreach(
$validators as $validator) {
                    switch (
$validator) {
                        
// If the validator is a numeric validator, we instantiate the validator
                        // with one or more target values.
                        
case 'Zend_Validate_GreaterThan':
                        case 
'Zend_Validate_LessThan':
                            
$validatorChain->addValidator(new $validator($this->min));
                            break;

                        case 
'Zend_Validate_Between':
                            
$validatorChain->addValidator(new $validator($this->min$this->maxfalse));
                            break;

                        
// If the validator is a validator for files, we instantiate the validator
                        // and we use this file as a target.
                        
case 'Zend_Validate_File_FilesSize':
                        case 
'Zend_Validate_File_Size':
                        case 
'Zend_Validate_File_WordCount':
                            
// We update the template of the error message for the file size,
                            // because we only validate for the exact size.
                            
$message "Wrong value for file '%value%' but '%size%' detected";
                            
// break;

                        
case 'Zend_Validate_File_Crc32':
                        case 
'Zend_Validate_File_Extension':
                        case 
'Zend_Validate_File_Md5':
                        case 
'Zend_Validate_File_Sha1':
                            
$fileValidator = new $validator($data);
                            empty(
$message) or $fileValidator->setMessage($message);
                            
$validatorChain->addValidator($fileValidator);
                            
// And we perform the validation.
                            
$isValid $validatorChain->isValid(__FILE__);
                            break;

                        case 
'Zend_Validate_Identical':
                            
$validatorChain->addValidator(new $validator($this->identical));
                            break;

                        default:
                            
// If this is another validator, we simply add the validator.
                            
$validatorChain->addValidator(new $validator());
                    }
                }

                
// And we perform the validation if it has not been done yet.
                
isset($isValid) or $isValid $validatorChain->isValid($data);

                if (
$isValid) {
                    
$result 'Your text is valid!';
                } else {
                    
// We return the error message if the validation failed.
                    
$result $validatorChain->getMessages();
                    
$result str_replace(__FILE__basename(__FILE__), $result);
                }
            }

        } catch (
Exception $e) {
            
// If we catch an exception, we return the error message.
            
$result $e->getMessage();
        }

        
$validators array_pad($validators3null);

        return array(
$data$validators$result);
    }
Extraction of the parameters from the GET request
  • We ignore a validator if the validator is invalid.

    private function _getParameters()
    {
        
$data = isset($_GET['data'])? $_GET['data'] : null;

        
// We ignore a validator if the validator is invalid.
        
$validators = array();
        if (isset(
$_GET['validators'])) {
            foreach(
$_GET['validators'] as $validator) {
                (
in_array($validator$this->zendValidators) or
                
in_array($validator$this->customValidators)) and
                
$validators[] = $validator;
            }
        }

        return array(
$data$validators);
    }

}

No comments:

Post a Comment