lawrence/fast-validate

验证更快!

v1.12 2015-11-17 01:51 UTC

This package is not auto-updated.

Last update: 2024-09-18 10:22:22 UTC


README

使用 FastValidate 验证更快!

FastValidate 需要 Laravel >= 5.0

安装

要安装,只需运行 composer require lawrence/fast-validate

示例

下面是一个扩展自 BaseModel 的类的示例。

<?php

use FastValidate\BaseModel;

class User extends BaseModel {

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    public function getRulesAttribute(){
        return [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $this->id,
            'password' => 'required|min:8'
        ];
    }

    public function setPasswordAttribute($value){
        $this->attributes['password'] = bcrypt($value);
    }

}

下面是如何使用 User 类的示例。

<?php

// Creating a new model
$user = new User;
$user->saveFromInput();

// Updating a model
$user = User::where('name', '=', 'Super User')->firstOrFail();
$user->saveFromInput();

这种神奇之处在于通过钩入 保存 事件钩子。当一个模型开始保存时,它将从请求中获取所有相关输入,验证输入,然后使用输入填充模型。如果输入无效,将抛出包含大量验证错误的 ValidationException

为了提供这种神奇效果,对数据结构有要求。这种要求遵循格式 model_name.attribute_name。因此,对于上述 User 示例,我们需要按以下格式发送数据

<?php
Input::merge([
        'user.name' => 'Johnnie',
        'user.email' => 'john@theinternet.com',
        'user.password' => 'correcthorsebatterystaple'
]);

在上述 User 示例中,我们添加了一些复杂性。getRulesAttribute() 函数意味着我们可以动态地更改我们的验证规则。在这种情况下,我们想确保电子邮件是唯一的,但如果我们要更新具有相同电子邮件地址的模型,则 "unique:users,email,$this->id" 将避免此问题。

使用 setPasswordAttribute($value) 函数,我们可以验证提供的密码,然后保存密码的加密值。

有时您可能想要从输入创建多个模型。我们可以使用以下表单来完成此操作

<form action="create-users" method="post">
    <input type="text" name="user.name[]" value="Johnnie">
    <input type="text" name="user.email[]" value="john@theinternet.com">
    <input type="text" name="user.password[]" value="correcthorsebatterystaple">
    <input type="text" name="user.name[]" value="Tommie">
    <input type="text" name="user.email[]" value="tommie@theinternet.com">
    <input type="text" name="user.password[]" value="Tr0ub4dor&3">
</form>

这将产生以下数据

<?php
[
    'name' : ['Johnnie', 'Tommie'],
    'email': ['john@theinternet.com', 'tommie@theinternet.com'],
    'password': ['correcthorsebatterystaple', 'Tr0ub4dor&3']
]

然后让神奇的事情发生!

``php <?php $users = User::createFromInput();