jridgewell/form-validator

一个简单的HTML表单验证器

v1.1.2 2013-06-26 03:46 UTC

This package is not auto-updated.

Last update: 2024-09-23 13:26:20 UTC


README

FormValidator 允许您通过简单的基于规则的途径创建和验证表单。它使用了一个与 Rails' ActiveRecord 非常相似的 API。

基础知识

表单文件只是一个扩展 \FormValidator\Form 类的类。在这个例子中,表单验证器检查 name 是否不为空。

test.form.php(模型)

<?php
    use \FormValidator\Form;
    use \FormValidator\Validation;

    class TestForm extends \FormValidator\Form {
        public function __construct() {
            $this->validations = array( // Contains a hash array of form elements
                "name" => Validation::presence() // name field must contain something
            );
        }
    }
?>

index.php(控制器)

<?php
    require_once('test.form.php')
    $form = new TestForm();

    /* Checks if the form has submitted then the form is checked for validation against the rules contained
       within the $validations array of TestForm returning the validated data if its successful
     */

    if($form->hasPosted() && ($data = $form->validate())) {
        // Form passes validation, use the $data for validated POST data

    } else {
        // Form hasn't posted or hasn't passed validation, so we load our html file
        require_once('form.html.php');
    }
?>

form.html.php(视图)

    <form name='input' method='POST'>
    <?php $form->error('name', 'There was an error'); ?>

    Please Enter your name: <?php $form->input('name'); ?><br/>
    <?php $form->submit('Submit');?>
    </form>

关于视图

  1. 如果表单验证失败,通过使用 $form->input 方法,我们可以保留用户输入到该字段的任何值(除了密码字段)。
  2. 表单 必须 包含一个名称属性设置为表单类名称的字段(在我们的例子中为 name="TestForm")。使用 $form->submit 方法可以满足这一要求。

安装

通过 Composer

composer require "jridgewell/form-validator:1.*"

然后只需将 require 'vendor/autoload.php'; 添加到任何需要 FormValidator 的代码中。

验证数组

$validations 数组包含所有需要通过验证的表单字段和规则,以便表单有效。在上面的例子中,它显示了一个应用于一个表单元素的单一规则,但您可以通过使用数组将多个规则应用于一个元素。

<?php
    class TestForm extends Form{
        public function __construct() {
            $this->validations = array(
                'name' => Validation::presence(),
                'age'   => array( //Specifiy multiple rules
                    Validation::presence(),
                    Validation::numericality()
                )
            );
        }
    }
?>

在我们的 HTML 文件中,如果我们想显示验证的错误,我们可以这样做:

<?php
    <form name='input' method='POST'>
    <?php $form->error('name', 'There was an error'); ?>

    Please Enter your name: <?php $form->input('name'); ?><br/>

    <?php $form->error('age', 'This is an optional custom message about age'); ?>

    Please Enter your age: <?php $form->input('age'); ?><br/>
    <?php $form->submit('Submit');?>
    </form>
?>

验证数组选项

大多数验证也支持传递一个选项数组。这允许自定义消息,并允许字段为可选(空白)。请参阅验证以了解可接受的参数。

<?php
    class TestForm extends Form {
        public function __construct() {
            $this->validations = array(
                'name' => Validation::length(array(
                    'minimum'  => 0,
                    'maximum' => 100
                )),
                'age'   => Validation::numericality(array(
                    'optional' => true,
                    'only_integer' => true
                )),
                'username' => Validation::exclusion(array(
                    'admin',
                    'superuser'
                ), array(
                    'message' => 'You are not our master!'
                ))
            );
        }
    }
?>

验证列表

简单验证

高级验证(需要参数)

高级验证示例

Validation::confirmation($other_field_func)

<?php
    // TestForm.php
    class TestForm extends Form{
        public function __construct() {
            $this->validations = array(
                'password' => Validation::confirmation(function() {
                    return $_POST['password_confirmation'];
                })
            );
        }
    }
?>

Validation::exclusion($array)

<?php
    // TestForm.php
    class TestForm extends Form{
        public function __construct() {
            $this->validations = array(
                'usernames' => Validation::exclusion(array(
                    'admin',
                    'superuser'
                ))
            );
        }
    }
?>

Validation::format($regex)

<?php
    // TestForm.php
    class TestForm extends Form{
        public function __construct() {
            $this->validations = array(
                'mp3Url' => Validation::format('/\.mp3$/')
            );
        }
    }
?>

Validation::inclusion($array)

<?php
    class TestForm extends Form{
        public function __construct() {
            $this->validations = array(
                'usernames' => Validation::inclusion(array(
                    'Matt',
                    'Thor',
                    'Asa'
                ))
            );
        }
    }
?>

Validation::validateWith($func)

此验证需要一个(可调用的)回调。此回调将作为唯一参数提供提交的字段数据。回调可以返回 true 并使验证通过,或者返回任何其他内容,并将其用作字段的错误消息。

<?php
    class TestForm extends Form {
        public function __construct() {
            $this->validations = array(
                'checkCustom' => Validation::validateWith(function($val) {
                    if ($val === 'supahSecret') {
                        return true;
                    }
                    return (substr($val, 0, 2) == 'st');
                })
            );
        }
    }
?>