Giter VIP home page Giter VIP logo

validation's Introduction

Simple PHP class for Validation

This PHP class is useful to validate an HTML form fields.

⚠️ Do you use PSR-7? Try Embryo Validation, the new version of this repository.

Usage

require_once('Validation.php');

Typical Use

    $email = '[email protected]';
    $username = 'admin';
    $password = 'test';
    $age = 29;
    
    $val = new Validation();
    $val->name('email')->value($email)->pattern('email')->required();
    $val->name('username')->value($username)->pattern('alpha')->required();
    $val->name('password')->value($password)->customPattern('[A-Za-z0-9-.;_!#@]{5,15}')->required();
    $val->name('age')->value($age)->min(18)->max(40);
    
    if($val->isSuccess()){
    	echo "Validation ok!";
    }else{
    	echo "Validation error!";
        var_dump($val->getErrors());
    }

Simple Form HTML Use

    <?php $val = new Validation; ?>
    
    <form method="post" action="#">
    	<label for="name">Name:</label>
        <input type="text" name="name" pattern="<?php echo $val->patterns['words']; ?>" required>
        <label for="email">E-Mail:</label>
        <input type="email" name="email" required>
        <label for="tel">Telephone:</label>
        <input type="text" name="tel" pattern="<?php echo $val->patterns['tel']; ?>">
        <label for="message">Message:</label>
        <textarea name="message" cols="40" rows="6" required></textarea>
        <button type="submit">Send</button>
    </form>
    
    <?php 
    	
        if(!empty($_POST)){
    	
          $val->name('name')->value($_POST['name'])->pattern('words')->required();
          $val->name('e-mail')->value($_POST['email'])->pattern('email')->required();
          $val->name('tel')->value($_POST['tel'])->pattern('tel');
          $val->name('message')->value($_POST['message'])->pattern('text')->required();

          if($val->isSuccess()){
              echo 'Validation ok!';        
          }else{
              echo $val->displayErrors();
          }

      }
  
    ?>

Methods

Method Parameter Description Example
name $name Return field name name('name')
value $value Return value field value($_POST['name])
file $value Return $_FILES array file($_FILES['name'])
pattern $pattern Return an error if the input has a different format than the pattern pattern('text')
customPattern $pattern Return an error if the input has a different format than the custom pattern customPattern('[A-Za-z]')
required Returns an error if the input is empty required()
min $length Return an error if the input is shorter than the parameter min(10)
max $length Return an error if the input is longer than the parameter max(10)
equal $value Return an error if the input is not same as the parameter equal($value)
maxSize $value Return an error if the file size exceeds the maximum allowable size maxSize(3145728)
ext $value Return an error if the file extension is not same the parameter ext('pdf')
isSuccess Return true if there are no errors isSuccess()
getErrors Return an array with validation errors getErrors()
displayErrors Return Html errors displayErrors()
result Return true if there are no errors or html errors result()
is_int $value Return true if the value is an integer number is_int(1)
is_float $value Return true if the value is an float number is_float(1.1)
is_alpha $value Return true if the value is an alphabetic characters is_alpha('test')
is_alphanum $value Return true if the value is an alphanumeric characters is_alphanum('test1')
is_url $value Return true if the value is an url (protocol is required) is_url('http://www.example.com')
is_uri $value Return true if the value is an uri (protocol is not required) is_uri('www.example.com')
is_bool $value Return true if the value is an boolean is_bool(true)
is_email $value Return true if the value is an e-mail is_email('[email protected]')

Patterns

Name Description Example
uri Url without file extension folder-1/folder-2
url Uri with file extension http://www.example.com/myfile.gif
alpha Only alphabetic characters World
words Alphabetic characters and spaces Hello World
alphanum Alpha-numeric characters test2016
int Integer number 154
float Float number 1,234.56
tel Telephone number (+39) 081-777-77-77
text Alpha-numeric characters, spaces and some special characters Test1 ,.():;!@&%?
file File name format myfile.png
folder Folder name format my_folde
address Address format Street Name, 99
date_dmy Date in format dd-MM-YYYY 01-01-2016
date_ymd Date in format YYYY-MM-dd 2016-01-01
email E-Mail format [email protected]

validation's People

Contributors

christoxz avatar davidecesarano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validation's Issues

Invalid patterns

Hi there, I've started using your class since today.

for some reason I'm getting this error multiple times on the page Warning: preg_match(): Compilation failed: invalid range in character class at offset 13 in \wp-content\plugins\my_plugin\classes\Validation.php on line 99. And for some reason patterns like email don't accept normal emails like [email protected]. Also normal text fields need to have the pattern alpha to be accepted as valid.

Do you know how to solve this?

Return array key in input name

'[A-Za-z0-9-\/_?&=]+', 'url' => '[A-Za-z0-9-:.\/_?&=#]+', 'alpha' => '[\p{L}]+', 'words' => '[\p{L}\s]+', 'alphanum' => '[\p{L}0-9]+', 'int' => '[0-9]+', 'float' => '[0-9\.,]+', 'tel' => '[0-9+\s()-]+', 'text' => '[\p{L}0-9\s-.,;:!"%&()?+\'°#\/@]+', 'file' => '[\p{L}\s0-9-_!%&()=\[\]#@,.;+]+\.[A-Za-z0-9]{2,4}', 'folder' => '[\p{L}\s0-9-_!%&()=\[\]#@,.;+]+', 'address' => '[\p{L}0-9\s.,()°-]+', 'date_dmy' => '[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4}', 'date_ymd' => '[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}', 'email' => '[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+[.]+[a-z-A-Z]' ); /** * @var array $errors */ public $errors = array(); /** * Nome del campo * * @param string $name * @return this */ public function name($name){ $this->name = $name; return $this; } /** * Valore del campo * * @param mixed $value * @return this */ public function value($value){ $this->value = $value; return $this; } /** * File * * @param mixed $value * @return this */ public function file($value){ $this->file = $value; return $this; } /** * Pattern da applicare al riconoscimento * dell'espressione regolare * * @param string $name nome del pattern * @return this */ public function pattern($name){ if($name == 'array'){ if(!is_array($this->value)){ $this->errors[$this->name] = 'le format de votre '.$this->name.' n\'est pas valide.'; } }else{ $regex = '/^('.$this->patterns[$name].')$/u'; if($this->value != '' && !preg_match($regex, $this->value)){ $this->errors[$this->name] = 'le format de votre '.$this->name.' n\'est pas valide.'; } } return $this; } /** * Pattern personalizzata * * @param string $pattern * @return this */ public function customPattern($pattern){ $regex = '/^('.$pattern.')$/u'; if($this->value != '' && !preg_match($regex, $this->value)){ $this->errors[$this->name] = 'le format de votre '.$this->name.' n\'est pas valide.'; } return $this; } /** * Campo obbligatorio * * @return this */ public function required(){ if((isset($this->file) && $this->file['error'] == 4) || ($this->value == '' || $this->value == null)){ $this->errors[$this->name] = 'Votre '.$this->name.' est requis.'; } return $this; } /** * Lunghezza minima * del valore del campo * * @param int $min * @return this */ public function min($length){ if(is_string($this->value)){ if(strlen($this->value) < $length){ $this->errors[] = 'Valore campo '.$this->name.' inferiore al valore minimo'; } }else{ if($this->value < $length){ $this->errors[] = 'Valore campo '.$this->name.' inferiore al valore minimo'; } } return $this; } /** * Lunghezza massima * del valore del campo * * @param int $max * @return this */ public function max($length){ if(is_string($this->value)){ if(strlen($this->value) > $length){ $this->errors[] = 'Valore campo '.$this->name.' superiore al valore massimo'; } }else{ if($this->value > $length){ $this->errors[] = 'Valore campo '.$this->name.' superiore al valore massimo'; } } return $this; } /** * Confronta con il valore di * un altro campo * * @param mixed $value * @return this */ public function equal($value){ if($this->value != $value){ $this->errors[] = 'Valore campo '.$this->name.' non corrispondente.'; } return $this; } /** * Dimensione massima del file * * @param int $size * @return this */ public function maxSize($size){ if($this->file['error'] != 4 && $this->file['size'] > $size){ $this->errors[] = 'Il file '.$this->name.' supera la dimensione massima di '.number_format($size / 1048576, 2).' MB.'; } return $this; } /** * Estensione (formato) del file * * @param string $extension * @return this */ public function ext($extension){ if($this->file['error'] != 4 && pathinfo($this->file['name'], PATHINFO_EXTENSION) != $extension && strtoupper(pathinfo($this->file['name'], PATHINFO_EXTENSION)) != $extension){ $this->errors[] = 'Il file '.$this->name.' non è un '.$extension.'.'; } return $this; } /** * Purifica per prevenire attacchi XSS * * @param string $string * @return $string */ public function purify($string){ return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); } /** * Campi validati * * @return boolean */ public function isSuccess(){ if(empty($this->errors)) return true; } /** * Errori della validazione * * @return array $this->errors */ public function getErrors(){ if(!$this->isSuccess()) return $this->errors; } /** * Visualizza errori in formato Html * * @return string $html */ public function displayErrors(){ $html = '
    '; foreach($this->getErrors() as $error){ $html .= '
  • '.$error.'
  • '; } $html .= '
'; return $html; } /** * Visualizza risultato della validazione * * @return booelan|string */ public function result(){ if(!$this->isSuccess()){ foreach($this->getErrors() as $error){ echo "$error\n"; } exit; }else{ return true; } } /** * Verifica se il valore è * un numero intero * * @param mixed $value * @return boolean */ public static function is_int($value){ if(filter_var($value, FILTER_VALIDATE_INT)) return true; } /** * Verifica se il valore è * un numero float * * @param mixed $value * @return boolean */ public static function is_float($value){ if(filter_var($value, FILTER_VALIDATE_FLOAT)) return true; } /** * Verifica se il valore è * una lettera dell'alfabeto * * @param mixed $value * @return boolean */ public static function is_alpha($value){ if(filter_var($value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z]+$/")))) return true; } /** * Verifica se il valore è * una lettera o un numero * * @param mixed $value * @return boolean */ public static function is_alphanum($value){ if(filter_var($value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z0-9]+$/")))) return true; } /** * Verifica se il valore è * un url * * @param mixed $value * @return boolean */ public static function is_url($value){ if(filter_var($value, FILTER_VALIDATE_URL)) return true; } /** * Verifica se il valore è * un uri * * @param mixed $value * @return boolean */ public static function is_uri($value){ if(filter_var($value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[A-Za-z0-9-\/_]+$/")))) return true; } /** * Verifica se il valore è * true o false * * @param mixed $value * @return boolean */ public static function is_bool($value){ if(is_bool(filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE))) return true; } /** * Verifica se il valore è * un'e-mail * * @param mixed $value * @return boolean */ public static function is_email($value){ if(filter_var($value, FILTER_VALIDATE_EMAIL)) return true; } }

Error in checking in text

Check Out once this error ;

Warning: preg_match(): Compilation failed: invalid range in character class at offset 13 in C:\xampp\htdocs\practise\handicraft\validation.php on line 99

bad 'email' pattern

in $patterns array You should change email pattern to this

from
'email' => '[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+[.]+[a-z-A-Z]'

to
'email' => '[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+',

wrong length of unicode characters

strlen() is not handling multibyte characters correctly, as it assumes 1 char equals 1 byte, which is simply invalid for unicode.
The solution is to use mb_strlen() function

how to use some function?

Can not I figure out how to use some function?
for example:

is_email()
purify()
is_int()

Thank you for your kind help

Using ->purify() not working

Hi there, I've used your validation class a couple of times because it works really well, even with some custom methods of my own.
I normally start by doing
$val->name('fname')->value(htmlspecialchars($_REQUEST['fname']))->required();.
But then I figured out you had a purify method that does that for you in the code, I tried it by chaining it to my validation lines, but it gave me some bad responses. Although not sure what since I'm getting the data by JS via my PHP script.

I tried it like this:
$val->name('fname')->value($_REQUEST['fname'])->purify($_REQUEST['fname'])->required();.

Required validation for files is not right

It returns error even if a file is selected due to the || condition on the $value being NULL when testing files

if((isset($this->file) && $this->file['error'] == 4) || ($this->value == '' || $this->value == null)){}

I fixed it changing the condition to:

if( isset($this->file) ) { if ( $this->file['error'] == 4 ) $error = true; } else if( $this->value == '' || $this->value == null ) $error = true;

Sidenote: It is recommended to use a separate object to validate files, because some issues raise upon other data types validation along with file validation

Text Pattern is Bad

in $patterns array You should change text pattern to this

from
'text'          => '[\p{L}0-9\s-.,;:!"%&()?+\'°#\/@]+',
to
'text'          => '[a-zA-Z0-9.\s\d\w\D][^\'"]+',

Accepted any number characters except ' or "

Display errors in Engilsh

Hi, I am using this package in my project. And As I see, it is working fine as per my requirement. But the problem is when I try to display the errors, it is displaying errors in some other language. As shown below. Can you please help me to display these errors in English.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.