PHP Classes

Simple Form Validator: Validate forms with rules defined in the HTML

Recommend this page to a friend!
  Info   View files Example   View files View files (5)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 127 This week: 1All time: 9,384 This week: 560Up
Version License PHP version Categories
simpleformvalidator 1.0.0GNU General Publi...5HTML, PHP 5, Validation, Parsers
Description 

Author

This class can validate forms with rules defined in the HTML.

It takes the HTML text for a form and extracts the list of inputs and validation rules that they define.

The class performs the validation of submitted values using the previously extracted rules.

Picture of Jonas Earendel
Name: Jonas Earendel <contact>
Classes: 1 package by
Country: Sweden Sweden
Age: 49
All time rank: 191219 in Sweden Sweden
Week rank: 416 Up6 in Sweden Sweden Up
Innovation award
Innovation award
Nominee: 1x

Example

<?php
define
('LANGUAGE','en');
include
'class.SimpleFormValidator.php';

$form = new SimpleFormValidator(__DIR__.'/example.form.php');
if(!empty(
$_GET)){
    if(
$form->validate($_GET)){
       
$form->triggerCustomError('test[email][weird_name_just_to_prove_it_works]','Validation successful, custom error triggered.');
    }
}else{
   
$form->setValues(array(
       
'test' =>
            array (
               
'email' =>
                    array (
                       
'weird_name_just_to_prove_it_works' => 'validemail@test.com',
                       
'repeated' => 'validemail@test.com',
                    ),
               
'type_email' => 'validemail@test.com',
               
'password' => 'asdf',
               
'repeat_password' => 'asdf',
            ),
       
'a_radio_button' => 'något annat',
       
'foo' =>
            array (
               
'bar' => 'some_value',
            ),
       
'a_list' => 'ett konstigt värde',
       
'area' => 'ett konstigt värde',
    ));
}

?><!DOCTYPE html>
<html lang="en">
<head>
    <meta name="charset" content="UTF-8">
    <meta name="author" content="Jonas Earendel">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="PHP Form validation example.">
    <title>An example - SimpleFormValidator</title>
    <style>
    label{
        padding-top:1em;
        display: block;
        font-weight: bold;
    }
    .error {
        border:2px solid black;
    }
    .sfv{
        color:red;
    }
    </style>
</head>
<body>
    <h1>An example</h1>
    <p>
        In this example I use GET instead of POST. This makes it easier to manipulate values and trigger errors.
    </p>
    <p>
        I also have words in Swedish to test unicode characters, as well as a weird variable structure.
    </p>
    <p>
        (The form has the <b>novalidate</b> attribute, to ensure server side validation only.)
    </p>
    <form action="/example.php" method="get" novalidate>
<?php $form->html(); ?>

    </form>
</body>
</html>


Details

SimpleFormValidator

The purpose of SimpleFormValidator is to make user input validation secure, simple and fast.

No external rule declarations are necessary, or even possible.

SimpleFormValidator will instead extract the rules from the HTML using PHP's native DOMDocument class.

Just make sure you have valid HTML5 code, and it will work.

THE INGREDIENTS

Three ingredients are needed to make it work:

  • The base class. (SimpleFormValidator)
  • The texts file. (So error messages can be in any language.)
  • The form body. (This can be in a file or in a string containing the form.)

A BASIC EXAMPLE

The smallest example imaginable:

<?php
$form = new SimpleFormValidator('
  <input type="email" name="your_email" required>
  <input type="text" name="repeat_email" data-match="your_email">
');
if(!empty($_POST) && $form->validate($_POST)) {
    /do stuff; send e-mail, log in, redirect, etc./
} ?>
<form method="post" action="example.php">
    <?php $form->html(); ?>
</form>

>$_POST['your_email'] will be validated as an e-mail address. $_POST['your_email'] cannot be left empty. $_POST['repeat_email'] must match $_POST['your_email'], whether empty or not.

CUSTOM ERRORS

So, the user has entered a valid username and password, but they aren't correct.

That's when custom errors (triggerCustomError()) come in handy.

<?php
if(!empty($_POST) && $form->validate($_POST)) {
    if($user = User::fetch($_POST["username"])) {
        if($user->password == $_POST["password"]) {
            $_SESSION["user"] = $user->getAttributes();
            header("Location: welcome.php"); exit;
        } else {
            $form->triggerCustomError("password", "Password incorrect.");
        }
    } else {
        $form->triggerCustomError("username", "User not found.");
    }
} ?>
<form method="post" action="login.php">
    <?php $form->html(); ?>
</form>

PRESET VALUES

If for instance a user is logged in and wants to send an e-mail, you can pre-populate the form. (This saves a lot of time during development.)

<?php
if(!empty($_POST){
    if($form->validate($_POST))){/.../}
}else{
    $form->setValue("email",$_SESSION["user"]["email"]);
    $form->setValue("first_name",$_SESSION["user"]["first_name"]);
} ?>
<form method="post" action="contact.php">
    <?php $form->html(); ?>
</form>

EXTENSIBILITY

The base class does not have that many validators, just the ones I've had use for lately, but that is not the end of the story.

Enter: Inheritance.

Create your own class, extending SimpleFormValidator, and add the validators you want. The existing ones can all be found in the original's constructor, if you need hints.

Like so:

class MyValidator extends SimpleFormValidator {
    function __construct($html){
        parent::__construct($html);
        $this-> validators["number"]=function($name,$value,$node){};
        $this-> validators["zip"]=function($name,$value,$node){};
        /also add error messages to the sfv.texts_xx.php file/
    }
}

I do not recommend editing SimpleFormValidator directly, since there may be updates in the future.


  Files folder image Files  
File Role Description
Plain text file class.SimpleFormValidator.php Class Class source
Accessible without login Plain text file example.form.php Aux. Auxiliary script
Accessible without login Plain text file example.php Example Example script
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Plain text file sfv.texts_en.php Aux. Example script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:127
This week:1
All time:9,384
This week:560Up