PHP Classes

PHP HTML Form Validator: Validate submitted forms values with rules in HTML

Recommend this page to a friend!
  Info   View files Documentation   View files View files (29)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 230 This week: 1All time: 8,149 This week: 560Up
Version License PHP version Categories
html-form-validator 1.0.0MIT/X Consortium ...7HTML, Validation, Parsers, PHP 7
Description 

Author

This package can validate submitted forms values with rules in HTML.

It can take the HTML of a form and parses it to extract the form inputs and any rules defined in them.

The class validates the submitted form values to according to the extracted rules.

Picture of Lars Moelleken
  Performance   Level  
Name: Lars Moelleken <contact>
Classes: 25 packages by
Country: Germany Germany
Age: 36
All time rank: 62340 in Germany Germany
Week rank: 52 Up3 in Germany Germany Up
Innovation award
Innovation award
Nominee: 11x

Winner: 1x

Documentation

Build Status Coverage StatusScrutinizer Code Quality Codacy Badge Latest Stable Version Total Downloads Latest Unstable Version License

HTMLFormValidation

Description

HtmlFormValidator is a very easy to use PHP library that will help you to validate your `<form>` data.

We will use Respect/Validation in the background, so you can use this independent from your framework of choice.

Install via "composer require"

composer require voku/html-form-validator

Quick Start

use voku\HtmlFormValidator\Validator;

require_once 'composer/autoload.php';

$html = "
<form action="%s" id="register" method="post">
    <label for="email">Email:</label>
    <input
        type="email"
        id="email"
        name="user[email]"
        value=""
        data-validator="email"
        data-filter="trim"
        required="required"
    />
    
    <label for="username">Name:</label>
    <input
        type="text"
        id="username"
        name="user[name]"
        value=""
        data-validator="notEmpty|maxLength(100)"
        data-filter="strip_tags(<p>)|trim|escape"
        required="required"
    />
    
    <input type="submit"/>
</form>
";

$formValidator = new Validator($formHTML);

$formData = [
        'user' => [
            'email' => 'foo@isanemail',
            'name'  => 'bar',
        ],
    ];


// validate the form
$formValidatorResult = $formValidator->validate($formData);

// check the result
$formValidatorResult->isSuccess(); // false

// get the error messages
$formValidatorResult->getErrorMessages(); // ['user[email]' => ['"foo@isanemail" must be valid email']]    

Validator

You can use all validators from here.

e.g.: `data-validator="date"` (you need to lowercase the first letter from the class)

You can combine validators simply via "|" ...

e.g.: `data-validator="notEmpty|maxLength(100)"`

PS: you can add arguments comma separated or you can use serialize -> something like that -> `in(' . serialize($selectableValues) . ')`

If you wan't to use the HTML5 validation e.g. for min or max values, or for e.g. email then you can use "auto".

e.g.: `data-validator="auto"`

If you wan't to limit the submitted values to the values from the form e.g. for checkboxes or radios, then you can use "strict".

e.g.: `data-validator="strict"`

And if you need a more complex validation, then you can add simple-custom validations.

$formValidator->addCustomRule(
    'foobar',
    v::allOf(
        v::intVal(),
        v::positive()
    )
);

e.g.: `data-validator="foobar"`

And if you need really complex validation, then you can create your own classes.

<?php

namespace Respect\Validation\Rules;

class CustomRule extends AbstractRule
{
  /
   * @param string $value
   *
   * @return bool
   */
  public function validate($value)
  {
    return ($value === 'foobar');
  }

}

<?php

namespace Respect\Validation\Exceptions;

class CustomRuleException extends ValidationException
{
  public static $defaultTemplates = [
      self::MODE_DEFAULT  => [
          self::STANDARD => 'Invalid input... \'foobar\' is only allowed here... ', // eg: must be string
      ],
      self::MODE_NEGATIVE => [
          self::STANDARD => 'Invalid input... \'foobar\' is not allowed here... ', // eg: must not be string
      ],
  ];
}

$formValidator->addCustomRule('foobar', \Respect\Validation\Rules\CustomRule::class);

e.g.: `data-validator="foobar"`

Filter

You can also use some simple filters, that will be applied on the input-data.

  • trim
  • escape (htmlentities with ENT_QUOTES | ENT_HTML5)
  • ... and all methods from here

e.g.: `data-filter="strip_tags(<p>)"`

PS: the first argument will be the submitted value from the user

And also here you can combine some filters simply via "|" ...

e.g.: `data-filter="strip_tags|trim|escape"`

... and you can also add custom filters by your own.

$formValidator->addCustomFilter(
    'append_lall',
    function ($input) {
      return $input . 'lall';
    }
);

e.g.: `data-filter="append_lall"`

Unit Test

1) Composer is a prerequisite for running the tests.

composer install voku/HtmlFormValidator

2) The tests can be executed by running this command from the root directory:

./vendor/bin/phpunit

  Files folder image Files  
File Role Description
Files folder imagesrc (1 directory)
Files folder imagetests (1 file, 1 directory)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file .scrutinizer.yml Data Auxiliary data
Accessible without login Plain text file .styleci.yml Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file ISSUE_TEMPLATE.md Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file PULL_REQUEST_TEMPLATE.md Data Auxiliary data
Accessible without login Plain text file README.md Doc. Class source

  Files folder image Files  /  src  
File Role Description
Files folder imagevoku (1 directory)

  Files folder image Files  /  src  /  voku  
File Role Description
Files folder imageHtmlFormValidator (4 files, 2 directories)

  Files folder image Files  /  src  /  voku  /  HtmlFormValidator  
File Role Description
Files folder imageExceptions (5 files)
Files folder imageRules (4 files)
  Plain text file Validator.php Class Class source
  Plain text file ValidatorHelpers.php Class Class source
  Plain text file ValidatorResult.php Class Class source
  Plain text file ValidatorRulesManager.php Class Class source

  Files folder image Files  /  src  /  voku  /  HtmlFormValidator  /  Exceptions  
File Role Description
  Plain text file MaxLengthException.php Class Class source
  Plain text file MinLengthException.php Class Class source
  Plain text file NoValidationRule.php Class Class source
  Plain text file UnknownFilter.php Class Class source
  Plain text file UnknownValidationRule.php Class Class source

  Files folder image Files  /  src  /  voku  /  HtmlFormValidator  /  Rules  
File Role Description
  Plain text file Auto.php Class Class source
  Plain text file MaxLength.php Class Class source
  Plain text file MinLength.php Class Class source
  Plain text file Strict.php Class Class source

  Files folder image Files  /  tests  
File Role Description
Files folder imageunit (3 files)
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script

  Files folder image Files  /  tests  /  unit  
File Role Description
  Plain text file CustomRule.php Class Class source
  Plain text file CustomRuleException.php Class Class source
  Plain text file ValidatorTest.php Class Class source

Downloadhtml-form-validator-2017-12-17.zip 21KB
Downloadhtml-form-validator-2017-12-17.tar.gz 14KB
Install with ComposerInstall with Composer
Needed packages  
Class DownloadWhy it is needed Dependency
Portable UTF-8 Download .zip .tar.gz UTF-8 support Required
Simple HTML DOM Download .zip .tar.gz HTML-Dom interactions Required
 Version Control Unique User Downloads Download Rankings  
 100%
Total:230
This week:1
All time:8,149
This week:560Up