nia/form

表单组件用于验证数据是否符合表单的字段定义。

这个包的官方仓库似乎已经消失,因此该包已被冻结。

1.2.1 2017-06-05 20:22 UTC

This package is not auto-updated.

Last update: 2022-03-14 00:54:27 UTC


README

表单组件用于验证数据是否符合表单的字段定义。

安装

使用Composer安装此包。

    composer require nia/form

测试

要运行单元测试,请使用以下命令

$ cd /path/to/nia/component/
$ phpunit --bootstrap=vendor/autoload.php tests/

如何使用

以下示例展示了如何在简单的联系表单中使用表单组件。

    /**
     * Simple contact form validator implementation.
     */
    class ContactForm implements FormInterface
    {
        use FormTrait;

        /**
         * Constructor.
         */
        public function __construct()
        {
            // Allowed salutations: Mr, Mrs, Ms
            $this->addField('salutation', new InSetValidator([
                'Mr',
                'Mrs',
                'Ms'
            ]));

            // Name must be between 4 and 64 characters.
            $this->addField('name', new LengthValidator(4, 64), new TrimSanitizer());

            // Company is optional.
            $this->addField('company', new NullValidator(), new TrimSanitizer());

            // Email address needs to be well formed.
            $this->addField('email', new EmailAddressValidator(), new TrimSanitizer());

            // Message must be between 10 and 1024 characters.
            $this->addField('message', new LengthValidator(10, 1024), new TrimSanitizer());
        }
    }

    // [...]

    $form = new ContactForm();

    // This map will be filled with received, sanitized and validated data.
    $context = new Map();

    // Data to validate. Potential source: Nia\RequestResponse\RequestInterface implementations.
    $data = new Map([
        'salutation' => 'Mr',
        'name' => '  John Doe ',
        'company' => '',
        'email' => 'john.doe@my-domain.tld',
        'message' => ' Hello, this is John Doe! How are you??????      '
    ]);

    // Validate the data and fill up the context.
    $violations = $form->validate($data, $context);

    // Check whether the data is valid.
    if (count($violations) === 0) {
        // Okay, data valid so send the message via email or write into database.
    }

    // $context now looks like:
    //
    //    object(Nia\Collection\Map\StringMap\Map)#0 (1) {
    //      ["values":"Nia\Collection\Map\StringMap\Map":private]=>
    //      array(5) {
    //        ["salutation"]=>
    //        string(2) "Mr"
    //        ["name"]=>
    //        string(8) "John Doe"
    //        ["company"]=>
    //        string(0) ""
    //        ["email"]=>
    //        string(22) "john.doe@my-domain.tld"
    //        ["message"]=>
    //        string(42) "Hello, this is John Doe! How are you??????"
    //      }
    //    }