Smart and simple form validation with PHP

Introduction

In today’s world of software and application development, security is a key requirement of every web application.

Security is needed to protect your data and protect the end user from security vulnerabilities.

One of the first security measures to be considered is form validation. It means, you check every (if not all, at least the required/major) input fields to be sure the user has entered the values that meet your format. By checking these fields, at are little rest assured you are getting clean data from your user.

In this article, I am just going to show you a basic, simple but smart validation trick you can use in your PHP applications.

Background

I am sharing my own personnally developed validation class with you. I use it in all my apps.

This class can validate arrays of values according to given rules.

It can take definitions of rules to be applied to each entry of an array to be submitted with values to validate.

The class can take an array with values to validate with the previously defined rules.

It uses regular expressions to validate values by each rule. Currently it can validate values as email, URLs, IP addresses, integers, floats, booleans, minimum, maximum and exact length, and regular expression matching.

You can download the class from GitHub.

The class has two major methods, where all the tricks happen:

/**
 *
 * Add validation rule(s) to the given field. This is a chanable method.
 *
 * Note that a field must be unique in the $this->validations object.
 *
 * @param string $field Field to be validated
 * @param string $displayName The human friendly name for the given field
 * @param array $rules Rule(s) to apply to the given field
 *
 * @return void
*/
public function addRules($field, $displayName, $rules = []) {...}

and

/**

 *
 * Returns a true/false indicating the success or failure of the model validation.
 *
 * @param array @items The items to be validated. This in most cases, would be $_POST.
 *
 * @return boolean
 */
public function validated($items) {...}

Using the code

Download the file and copy it to your preferred directory in your application.

First, reference the file at the top of your source code.

require_once (path_to_the_file/KlinValidator.php’);Now, validate.

$validator = new KlinValidator();

$validator->addRules('firstName', 'first name', ['required', 'alphanum', 'minlen[3]', 'maxlen[50]'])
          ->addRules('age', 'age', ['required', 'int'])
          ->addRules('email', 'email', ['required', 'email'])
          ->addRules('password', 'password', ['required', 'minlen[6]'])
          ->addRules('confirmPassword', 'confirm password', ['required', 'matches[password]'])
 
 if ($validator->validated($_POST)) {
    echo 'Validation successful'; // or process the request
 } else {
    echo $validator->validationErrors;
 }

I hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *