PHP Classes

Hispanic Form Validation: Validate forms on the browser and server sides

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStarStar 69%Total: 202 All time: 8,465 This week: 455Up
Version License PHP version Categories
hispanic_validation 1.0.0GNU General Publi...5HTML, PHP 5, Validation
Description 

Author

This class can be used to validate forms on the browser and server sides.

It can take an array of validation rules and generates JavaScript to perform validation on the browser side of given form fields.

The class can generate validation JavaScript code using jQuery that is performed for different form events like when the form input is changed, the form loses focus, when a key is released, etc..

It can also perform validation of the submitted form input on the server side with the class PHP code.

Currently in can perform validation types like: required value, minimum length, maximum length, required file, file minimum and maximum size, file MIME type, image maximum width and height, checked checkbox, valid date and time format, IP address, valid email address, valid URL, match regular expression, maximum and minimum length, value equal to another input, valid number, minumum and maximum number, etc..

Picture of manudg
  Performance   Level  
Name: manudg <contact>
Classes: 6 packages by
Country: Spain Spain
Age: 43
All time rank: 158433 in Spain Spain
Week rank: 180 Up6 in Spain Spain Up

Example

<?php

require "../src/Validation.php";

use
Hispanic\Validation;

$validation = new Validation();
$attributes = array(
   
"repeat_password" => "Repeat Password",
);

$validation->attributes($attributes);
$rules = array(
   
"name" => "required|min_length:2|max_length:50|name",
   
"file" => "file_required|mime:pdf|file_min_size:".(20)."|file_max_size:".(1024*1024),
   
"files" => "file_required|min_files:2|max_files:3|mime:png,jpg|file_min_size:1000|file_max_size:".(1024*1024),
   
"image" => "file_required|mime:png,jpg|img_max_width:140|img_max_height:140",
   
"check" => "checked",
   
"date" => "required|date:Y/m/d",
   
"time" => "required|time:H:i:s",
   
"datetime" => "required|datetime:Y/m/d H:i:s",
   
"ip" => "required|ip",
   
"email" => "required|email",
   
"url" => "required|url",
   
"regex" => "required|regex:/^[a-z]+$/",
   
"password" => "required|between:6-30",
   
"repeat_password" => "required|equalsTo:password",
   
"float" => "required|float",
   
"integer" => "required|integer",
   
"numeric" => "required|numeric",
   
"between" => "required|between:10-20",
   
"range" => "required|range:1-10",
   
"contains" => "required|contains:one,two,three",
);

$messages = array(
   
//"name.required" => "El campo :attribute es requerido",
    //"name.min_length" ...
);
    
$events = array(
   
"name" => "keyup|blur|change",
   
"file" => "change",
   
"files" => "change",
   
"check" => "click",
   
"date" => "keyup|blur|change",
   
"time" => "keyup|blur|change",
   
"datetime" => "keyup|blur|change",
   
"ip" => "keyup|blur|change",
   
"email" => "keyup|blur|change",
   
"url" => "keyup|blur|change",
   
"regex" => "keyup|blur|change",
   
"repeat_password" => "keyup|blur|change",
   
"float" => "keyup|blur|change",
   
"integer" => "keyup|blur|change",
   
"numeric" => "keyup|blur|change",
   
"between" => "keyup|blur|change",
   
"range" => "keyup|blur|change",
   
"contains" => "keyup|blur|change",
);

$validation->translate("en");
$validation->client($rules, $messages, $events);
$errors = null;
$first_error = null;
if (isset(
$_POST["name"])) {
   
$validation->server($rules, $messages);
    if (!
$validation->isValid()) {
       
$errors = $validation->getErrors();
       
$first_error = $validation->getFirstError();
    }
}
?>
<!DOCTYPE HTML>
<html>
    <head>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
       
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
        <script type="text/javascript" src="../js/validation.js"></script>
    </head>
    <body>
    <div class="container">
        <br /><br />
        <?php print_r($errors) ?>
<form method="post" action="" id="form" enctype="multipart/form-data" class="form-horizontal">
            <div class="form-group">
                <label for="name">Name: <small>"name" =&gt; "required|min_length:2|max_length:50|name"</small></label>
                <input type="text" name="name" id="name" class="form-control" value="" />
                <p id="error_name"></p>
            </div>
            <div class="form-group">
                <label for="file">File: <small>"file" =&gt; "file_required|mime:pdf|file_min_size:".(20)."|file_max_size:".(1024*1024)</small></label>
                <input type="file" name="file" id="file" class="form-control" />
                <p id="error_file"></p>
            </div>
            <div class="form-group">
                <label for="files">File Multiple: <small>"files" =&gt; "file_required|min_files:2|max_files:3|mime:png,jpg|file_min_size:1000|file_max_size:".(1024*1024)</small></label>
                <input type="file" name="files[]" id="files" multiple class="form-control" />
                <p id="error_files"></p>
            </div>
            <div class="form-group">
                <label for="image">Image: <small>"image" =&gt; "file_required|mime:png,jpg|img_max_width:140|img_max_height:140"</small></label>
                <input type="file" name="image" id="image" class="form-control" />
                <p id="error_image"></p>
            </div>
            <div class="form-group">
                <label for="check">
                    <input type="checkbox" name="check" id="check" /> Checkbox <small>"check" =&gt; "checked"</small>
                </label>
                <p id="error_check"></p>
            </div>
            <div class="form-group">
                <label for="date">Date: <small>"date" =&gt; "required|date:Y/m/d"</small></label>
                <input type="text" name="date" id="date" class="form-control" />
                <p id="error_date"></p>
            </div>
            <div class="form-group">
                <label for="time">Time: <small>"time" =&gt; "required|time:H:i:s"</small></label>
                <input type="text" name="time" id="time" class="form-control" />
                <p id="error_time"></p>
            </div>
            <div class="form-group">
                <label for="datetime">DateTime: <small>"datetime" =&gt; "required|datetime:Y/m/d H:i:s"</small></label>
                <input type="text" name="datetime" id="datetime" class="form-control" />
                <p id="error_datetime"></p>
            </div>
            <div class="form-group">
                <label for="ip">Ip: <small>"ip" =&gt; "required|ip"</small></label>
                <input type="text" name="ip" id="ip" class="form-control" />
                <p id="error_ip"></p>
            </div>
            <div class="form-group">
                <label for="email">Email: <small>"email" =&gt; "required|email"</small></label>
                <input type="text" name="email" id="email" class="form-control" />
                <p id="error_email"></p>
            </div>
            <div class="form-group">
                <label for="url">Url: <small>"url" =&gt; "required|url"</small></label>
                <input type="text" name="url" id="url" class="form-control" />
                <p id="error_url"></p>
            </div>
            <div class="form-group">
                <label for="regex">Regex: <small>"regex" =&gt; "required|regex:/^[a-z]+$/"</small></label>
                <input type="text" name="regex" id="regex" class="form-control" />
                <p id="error_regex"></p>
            </div>
            <div class="form-group">
                <label for="password">Password: <small>"password" =&gt; "required|between:6-30"</small></label>
                <input type="password" name="password" id="password" class="form-control" />
                <p id="error_password"></p>
            </div>
            <div class="form-group">
                <label for="repeat_password">Repeat password: <small>"repeat_password" =&gt; "required|equalsTo:password"</small></label>
                <input type="password" name="repeat_password" id="repeat_password" class="form-control" />
                <p id="error_repeat_password"></p>
            </div>
            <div class="form-group">
                <label for="float">Float: <small>"float" =&gt; "required|float"</small></label>
                <input type="text" name="float" id="float" class="form-control" />
                <p id="error_float"></p>
            </div>
            <div class="form-group">
                <label for="integer">Integer: <small>"integer" =&gt; "required|integer"</small></label>
                <input type="text" name="integer" id="integer" class="form-control" />
                <p id="error_integer"></p>
            </div>
            <div class="form-group">
                <label for="numeric">Numeric: <small>"numeric" =&gt; "required|numeric"</small></label>
                <input type="text" name="numeric" id="numeric" class="form-control" />
                <p id="error_numeric"></p>
            </div>
            <div class="form-group">
                <label for="between">Between: <small>"between" =&gt; "required|between:10-20"</small></label>
                <input type="text" name="between" id="between" class="form-control" />
                <p id="error_between"></p>
            </div>
            <div class="form-group">
                <label for="range">Range: <small>"range" =&gt; "required|range:1-10"</small></label>
                <input type="text" name="range" id="range" class="form-control" />
                <p id="error_range"></p>
            </div>
            <div class="form-group">
                <label for="contains">Contains: <small>"contains" =&gt; "required|contains:one,two,three"</small></label>
                <input type="text" name="contains" id="contains" class="form-control" />
                <p id="error_contains"></p>
            </div>
            <button class="btn btn-default">Send</button>
        </form>
        <br /><br />
    </div>
        <?php echo $validation->getClientValidation("#form") ?>
</body>
</html>


Details

validation

<h3>This class can be used to validate forms on the browser and server sides.</h3>

<p> It can take an array of validation rules and generates JavaScript to perform validation on the browser side of given form fields. </p> <p> The class can generate validation JavaScript code using jQuery that is performed for different form events like when the form input is changed, the form loses focus, when a key is released, etc.. </p> <p> It can also perform validation of the submitted form input on the server side with the class PHP code. Currently in can perform validation types like: required value, minimum length, maximum length, required file, file minimum and maximum size, file MIME type, image maximum width and height, checked checkbox, valid date and time format, IP address, valid email address, valid URL, match regular expression, maximum and minimum length, value equal to another input, valid number, minumum and maximum number, etc.. </p>

<strong>Important: for client-side validation it is necessary to include jQuery and file <a href="https://github.com/hispanicode/validation/tree/master/js">validation.js</a></strong>

<p>Install with composer</p> <div class="highlight highlight-source-php"> <pre> composer require hispanicode/validation </pre> </div>

<p> <a href="http://hispanicode.com/home/pages/hispanicodevalidation-Modelo-de-validacion-de-formularios-del-lado-del-cliente-y-del-servidor-con-php-y-jQuery" target="_blank">Online example</a> </p>

<h3>Simple usage</h3>

<p>Require the class file</p> <div class="highlight highlight-source-php"> <pre> require "src/Validation.php"; /* if install with composer require "vendor/autoload.php"; */ </pre> </div>

<p>New instance</p> <div class="highlight highlight-source-php"> <pre> use Hispanic\Validation; $validation = new Validation(); </pre> </div>

<p>Rules</p> <div class="highlight highlight-source-php"> <pre> $rules = array( "name" => "required|name|min_length:3|max_length:50", "email" => "required|email|min_length:6|max_length:80", "password" => "required|between:6-30", "confirm_password" => "required|equalsTo:password", "terms" => "checked", ); </pre> </div>

<p>Optional. Custom messages. For example translate in other language (French)</p> <div class="highlight highlight-source-php"> <pre> $messages = array( "name.required" => "Le champ :attribute est obligatoire", /.../ ); </pre> </div>

<p>The default messages in distinct languages is possible in the <a href="https://github.com/hispanicode/validation/tree/master/src/translate">language.php</a> file. The spanish and english translates are availables but you can translate in your language.</p>

<div class="highlight highlight-source-php"> <pre> //The default translate is "en" in this case not is need use the translate method. //Translate in spanish $validation->translate("es"); </pre> </div>

<p>In the client validation is possible handle javascript events</p> <div class="highlight highlight-source-php"> <pre> $events = array( "name" => "keyup|blur|change", /.../ ); </pre> </div>

<p>Start the client validation</p> <div class="highlight highlight-source-php"> <pre> //The $messages and $events params are optionals $validation->client($rules, $messages, $events); </pre> </div>

<p>Generate the client validation is easy</p> <div class="highlight highlight-source-php"> <pre> //The argument is the id of the form echo $validation->getClientValidation("#form"); </pre> </div>

<p>For get the client messages set the next structure based in the bootstrap css styles</p> <div class="highlight highlight-source-html"> <pre> &lt;form method="post" id="form"&gt;

&lt;div class="form-group"&gt;
    &lt;label for="name"&gt;Name:&lt;/label&gt;
    &lt;input type="text" name="name" id="name" class="form-control" value="" /&gt;
    &lt;p id="error_name"&gt;&lt;/p&gt;
&lt;/div&gt;
...

&lt;/form&gt; </pre> </div>

<p>For the server side is the server() method</p> <div class="highlight highlight-source-php"> <pre>

use Hispanic\Validation;

$validation = new Validation();

//Is possible change the labels attributes with the attribute() method $attributes = array( "name" => "Name", "confirm_password" => "Confirm Password", /.../ );

$validation->attributes($attributes);

$rules = array( "name" => "required|regex:/^[a-z]+$/|min_length:3|max_length:50", /.../ );

/if you like the client validation is easy/ $validation->client($rules);

/request/ if (isset($_POST["name"])) { $validation->server($rules); //The second argument is optional for the custom messages array

//If is valid if ($validation->isValid()) {

  /ok/

} else {

/error/
//get associative array with all errors
$errors = $validation->getErrors();
//get only one error, the first error.
$first_error = $validation->getFirstError();

} } </pre> </div>

<h3>Validation rules options</h3> <ul> <li><strong>required</strong> : the field is required</li> <li><strong>checked</strong> : the field needs to be checked</li> <li><strong>min_length</strong> : minimum length of characters in string. Example: <i>min_length:3</i></li> <li><strong>max_length</strong> : maximum length of characters in string. Example: <i>max_length:30</i></li> <li><strong>min</strong> : minimum numeric value. Example: <i>min:1</i></li> <li><strong>max</strong> : maximum numeric value: Example: <i>max:10</i></li> <li><strong>between</strong> : range of characters allowed. Example: <i>between:3-20</i></li> <li><strong>range</strong> : range of allowable numeric values. Example: <i>range:1-10</i></li> <li><strong>name</strong> : only allowed a-záéíóúàèìòùäëïöüâêîôûñ\s. <i>(ignored uppercase)</i></li> <li><strong>alpha</strong> : only allowed a-záéíóúàèìòùäëïöüâêîôûñ <i>(ignored uppercase)</i></li> <li><strong>alphanumeric</strong> : only allowed 0-9a-záéíóúàèìòùäëïöüâêîôûñ <i>(ignored uppercase)</i></li> <li><strong>digit</strong> : only digits</li> <li><strong>email</strong> : only a valid email</li> <li><strong>ip</strong> : only a valid ip</li> <li><strong>url</strong> : only a valid url</li> <li><strong>date</strong> : only a valid date format. Example: <i>date:Y-m-d</i></li> <li><strong>time</strong> : only a valid time format. Example: <i>time:H:i:s</i></li> <li><strong>datetime</strong> : only a valid datetime format. Example: <i>datetime:Y-m-d H:i:s</i></li> <li><strong>regex</strong> : regular expression filter. Example: <i>regex:/^[a-z]$/i</i></li> <li><strong>equalsTo</strong> : The field value is equal to other field. Example: <i>equalsTo:password</i></li> <li><strong>float</strong> : only a float value</li> <li><strong>integer</strong> : only a integer value</li> <li><strong>numeric</strong> : only a numeric value</li> <li><strong>contains</strong> : the field needs to contain one of the required values. Example: <i>contains:one,two,three</i></li> <li><strong>file_required</strong> : the input file is required</li> <li><strong>min_files</strong> : minimum number of files allowed in input file multiple. Example: <i>min_files:2</i></li> <li><strong>max_files</strong> : maximum number of files allowed in input file multiple. Example: <i>max_files:10</i></li> <li><strong>file_min_size</strong> : minimum size allowed for file. Example 1MB: <i>file_min_size:1048576</i></li> <li><strong>file_max_size</strong> : maximum size allowed for file. Example 1024 bytes: <i>file_min_size:1024</i></li> <li><strong>mime</strong> : mime type allowed for file. Example: <i>mime:pdf,txt,js</i></li> <li><strong>img_min_width</strong> : minimum width allowed for image file. Example 250px: <i>img_min_width:250</i></li> <li><strong>img_max_width</strong> : maximum width allowed for image file. Example 1024px: <i>img_max_width:1024</i></li> <li><strong>img_min_height</strong> : minimum height allowed for image file. Example 250px: <i>img_min_height:250</i></li> <li><strong>img_max_height</strong> : maximum height allowed for image file. Example 1024px: <i>img_max_height:1024</i></li> </ul>


  Files folder image Files (6)  
File Role Description
Files folder imageexample (1 file)
Files folder imagejs (1 file)
Files folder imagesrc (1 file, 1 directory)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (6)  /  example  
File Role Description
  Accessible without login Plain text file example.php Example Example script

  Files folder image Files (6)  /  js  
File Role Description
  Accessible without login Plain text file validation.js Data Auxiliary data

  Files folder image Files (6)  /  src  
File Role Description
Files folder imagetranslate (1 file)
  Plain text file Validation.php Class Class source

  Files folder image Files (6)  /  src  /  translate  
File Role Description
  Accessible without login Plain text file translate.php Aux. Auxiliary script

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:202
This week:0
All time:8,465
This week:455Up
User Ratings User Comments (1)
 All time
Utility:91%StarStarStarStarStar
Consistency:91%StarStarStarStarStar
Documentation:66%StarStarStarStar
Examples:75%StarStarStarStar
Tests:-
Videos:-
Overall:69%StarStarStarStar
Rank:354
 
Pretty nice idea.
8 years ago (Thomas Horst)
72%StarStarStarStar