File: README.md

Recommend this page to a friend!
  Classes of Lars Moelleken  >  PHP HTML Form Validator  >  README.md  >  Download  
File: README.md
Role: Documentation
Content type: text/markdown
Description: Class source
Class: PHP HTML Form Validator
Validate submitted forms values with rules in HTML
Author: By
Last change:
Date: 3 years ago
Size: 5,724 bytes
 

Contents

Class file image Download

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
For more information send a message to info at phpclasses dot org.