Simple Form Validator

Documentation for v1.0 and later


Introduction

This is a technical documentation addressed to developers having to deal with this class, used in all LCweb WordPress plugins.
This is a form data validation class, targeting $_POST, $_GET, $_REQUEST and $_FILES globals.

Because of this, is essential to use and target unique form field indexes.

Basic Usage

Assuming you have the following form:

<form action="#" method="post">     
    <label>Name</label>
    <input type="text" name="name" maxlength="25" />

    <label>Surname (required)</label>
    <input type="text" name="surname" maxlength="30" />

    <input type="submit" name="form_btn" value="Validate" />
</form>

We want to get the form data and check that "Surname" field has been inserted.
Name can be long 25 characters and Surname 30.

PHP code:

if(isset($_POST["form_btn"])) {
    $validator = new simple_fv;

    // fields info container
    $fields = array(); 

    // fill the container with fields data
    $fields[] = array("index"=>"name", "label"=>"Name", "max_len"=>25);
    $fields[] = array("index"=>"surname", "label"=>"Surname", "required"=>true, "max_len"=>30);

    // validate the fields
    $validator->formHandle($fields);

    // get errors
    $error = $validator->getErrors();

    // if errors is not FALSE - print the successfull message
    echo ($error) ? $error : "SUCCESSFULL MESSAGE";
}

Explaining in words:

  • Include the class file
  • If form has been submitted, initialize the class
  • Create an array and populate it with many associatives array related to fields

This array defines which fields to search for and how to validate them.
Each field's associative array has:

  • "index" (required) - name of the field to catch
  • "label" (required) - field label that will eventually appear in errors string
  • validation parameters - instructions to validate the field. If no parameters are specified, the class simply stores the field value

After having created the fields array, simply call the validator method:

$validator->formHandle($indexes);

Doing so, the class stores both field values and the errors.
To seek for errors, use the getErrors() method.

Not having errors it will return FALSE, otherwise the HTML error messages, ready to be printed.

As you would do with $_POST or $_GET variables, array fields must be written without the "[]".
Each array element will be validated as a single entity.

The class automatically recognizes the array field structure and will accordignly return an array

Validator Parameters List

Here's the list of parameters you can use in the associative array for each form field:

Global ones:

Name Data Type Description Example
required boolean Require the field "required"=>true
min_len integer Set the minimum number of characters allowed "min_len"=>20
max_len integer Set the maximum number of characters allowed "max_len"=>100
right_len integer Set the exact number of characters allowed "right_len"=>50
allowed array Set field's allowed values "allowed"=>array("val_1", "val_2", 15, 56)
forbidden array Set field's the forbidden values "forbidden"=>array("val_1", "val_2", 15, 56)
preg_match regex string Define field's allowed pattern
(note the value will be used with preg_match() function)
"preg_match"=>"/[^a-z_]/i"
equal field name Set the field to compare with. It's useful for example to check password repeats "equal"=>"FIELD NAME"

Numeric ones:

Name Data Type Description Example
min_val integer Set field's the minimum value "min_val"=>10
max_val integer Set field's maximum value "max_val"=>100

Standard Data Type:

(Followings parameters check whether field value matches its data type)

Data Type Example
Integer number "type"=>"int"
Floating number "type"=>"float"
Negative Integer Number "type"=>"negative_int"
Valid E-mail "type"=>"email"
European date (DD MM YYYY) "type"=>"eu_date"
American date (MM DD YYYY) "type"=>"us_date"
ISO date (YYYY MM DD) "type"=>"iso_date"
Standard time (HH MM) "type"=>"time"
Valid URL "type"=>"url"
Valid Hexadecimal Color "type"=>"hex"
Valid IP Address "type"=>"ipv4"
Valid US ZIPCODE "type"=>"us_zipcode"
Valid US telephone "type"=>"us_tel"

Array ones:

Name Data Type Description Example
min_array integer Set the minimum number of array elements "min_array"=>5
max_array integer Set the maximum number of array elements "max_array"=>10

Upload ones:

Name Data Type Description Example
ul_required boolean Require the upload "ul_required"=>true
min_filesize integer Set the minimum filesize (in KILOBYTE) allowed "min_filesize"=>100
max_filesize integer Set the maximum filesize (in KILOBYTE) allowed "min_filesize"=>1000
mime_type array Set which files mime-type are allowed "mime_type"=>array("image/jpeg", "image/png")

THe "OR" Condition

Through the OR condition it's possible to perform advanced validations, allowing multiple combinations for each field.
In few words, the validation has no errors if at least one condition is true.

The following example will validate the form only if:

  • The field "or_1" is no longer than 20 characters
  • OR the field "or_1" is a valid integer
  • OR the field "or_2" is no longer than 30 characters
// create the  array
$or[] = array("index"=>"or_1", "required"=>true, "max_len"=>20);
$or[] = array("index"=>"or_1", "required"=>true, "type"=>int);
$or[] = array("index"=>"or_2", "required"=>true, "max_len"=>30);

// validate
$validator->or_cond("Fields", "You have to fill at least a field", $or);

// get errors
$error = $validator->getErrors();

// if errors is not FALSE - print the successfull message
echo ($error) ? $error : "SUCCESSFULL MESSAGE";

or_cond() method must be filled with:

  1. The error subject
  2. The error text
  3. The fields data array (as for standard validations)

Fields associaive array DOESN'T HAVE the "label" index

Get Form Data

Once form has been validated, field values are stored as an associative array in the form_val class property.
Assuming to have this form:

<form action="#" method="post">     
    <label>Name</label>
    <input type="text" name="name"/>

    <label>Surname</label>
    <input type="text" name="surname" />

    <input type="submit" name="form_btn" value="Validate" />
</form>

And this validation code:

$fields[] = array("index"=>"name", "label"=>"Name");
$fields[] = array("index"=>"surname", "label"=>"Surname");

$validator->formHandle($fields);

To get the form data you just have to code this:

$fv = $validator->form_val;
        
echo $fv["name"]; // print the name field value 
echo $fv["surname"]; // print the surname field value

Upload fields

In case of upload fields, the array index will contain the $_FILES variable.
For example, assuming to have this form:

<form method="post" action="#" enctype="multipart/form-data">      
    <input type="file" name="upload_file" />
    <input type="submit" name="submit_ul" value="Validate" />
</form>

The relative $fv["upload_file"] will contain the same data of $_FILES["upload_file"]

Get Escaped Fields

To get the form data already escaped (through addslashes()) and ready to be used with SQL queries, you have to call the following method:

$fv = $validator->escape_val();

Get Error Messages

Validation errors are grouped by error subject (eg. text length) and then list faulty field names

As written in the first chapter, to the seek for validation errors, you must use the getErrors() method
The class has got two output ways: returning an errors array or a string.

// getting errors string
$errors = $validator->getErrors();

// getting errors array
$errors_array = $validator->getErrors("array");