srlabs/validator

此包已废弃,不再维护。未建议替代包。

Laravel 4 表单验证类

v1.0.2 2016-02-29 23:46 UTC

This package is auto-updated.

Last update: 2022-02-01 12:39:23 UTC


README

No Maintenance Intended

Laracasts 表单验证器启发,此包提供了一种简单的方法来验证表单数据,包括对唯一值的检查。

此包已不再维护。

安装

应通过 composer 安装此包

$ composer require srlabs/validator

使用

要使用表单验证器,首先创建一个继承自 SRLabs\Validator\Validation\FormValidator 的表单类。此类将指定验证此表单时希望使用的规则和自定义消息。例如

<?php namespace Epiphyte\Forms;

use SRLabs\Validator\Validation\FormValidator;

class UpdateProductionForm extends FormValidator {

    protected $rules = array(
        'name' => 'required|alpha|unique:productions',
        'author' => 'required'
    );

    protected $messages = array(
        'name.unique' => 'There is already a production with that name.'
    );
}

然后,将自定义表单类注入到处理表单提交的控制器中。

<?php

use Epiphyte\Forms\CreateProductionForm;
use Epiphyte\Forms\UpdateProductionForm;

class ProductionController extends \BaseController {

    protected $createProductionForm;
    protected $updateProductionForm;

    /**
     * @param CreateProductionForm $createProductionForm
     */
    public function __construct(
        CreateProductionForm $createProductionForm,
        UpdateProductionForm $updateProductionForm)
    {
        $this->createProductionForm = $createProductionForm;
        $this->updateProductionForm = $updateProductionForm;
    }

    // ...
}

在控制器方法中执行此操作以验证表单数据

public function store()
{
    // Gather the Data
    $data = Input::only('name', 'author');

    // Validate the Form
    $this->createProductionForm->validate($data);

    // Create the Production
    Epiphyte\Production::create($data);

    Session::flash('success', 'Production Added');
    return Redirect::action('ProductionController@index');
}

请注意,如果验证失败,将抛出(并随后捕获)异常,强制将表单重定向回,同时发送错误消息和旧输入。

要验证包含 unique 规则的字段,将相应的对象传递给表单类

public function update($id)
{
    $production = Epiphyte\Production::find($id);
    $data = Input::only('name', 'author');

    $this->updateProductionForm->validate($data, $production);

    $production->name = $data['name'];
    $production->author = $data['author'];
    $production->save();

    Session::flash('success', 'Production Updated');
    return Redirect::action('ProductionController@index');
}

路线图

  • 需要完善和大幅提高测试。
  • 最终我将添加一些配置选项。