简化Laravel中的验证。

dev-master 2016-02-14 08:53 UTC

This package is auto-updated.

Last update: 2024-08-28 23:58:19 UTC


README

一个轻量级的库,使用Laravel PHP框架简化数据验证。

使你的模型能够自我验证,只需在Eloquent模型中定义验证规则。每次尝试使用模型创建或更新数据且验证失败时,将抛出异常。

安装

将以下内容添加到require部分(在你的composer.json文件中)

"usmanhalalit/dryval": "1.*@dev"

然后运行:composer update。库位于Packagist

使用示例

use Dryval\ValidationTrait;

class Campaign extends Eloquent {
    use ValidationTrait;

    protected static $rules = [
        'title' => 'required|min:5|max:50', // `title` is the field in your table
        'description' => 'required|min:5|max:500',
    ];

}

现在每次验证规则违反时,都会抛出Dryval\ValidationException异常。

Laravel 5

要捕获此异常,请将以下代码放入你的app/Exceptions/Handler.php文件的render()方法中。它将看起来像这样

public function render($request, Exception $e)
{
    try {
        return \Redirect::back()->with('error', $e->getMessages()->first())->withInput(\Input::except('password'));
    } catch (Exception $exception) {
        // Fallback if referer doesn't exist
        return \Redirect::to('/')->with('error', $e->getMessages()->first())->withInput(\Input::except('password'));
    }
}

Laravel 4

将以下代码放入你的app/start/global.php文件中

App::error(function(\Dryval\ValidationException $e)
{
    try {
        return \Redirect::back()->with('error', $e->getMessages()->first())->withInput(\Input::except('password'));
    } catch (Exception $exception) {
        // Fallback if referer doesn't exist
        return \Redirect::to('/')->with('error', $e->getMessages()->first())->withInput(\Input::except('password'));
    }
});

这将设置一个具有键error的消息。你可以随意操作。就这么简单。

现在你不必在所有地方验证输入。只需保存数据,它将自动验证。DRYVal利用PHP 5.4特性来实现这一点。因此,你不必扩展类。

更多使用方法

自定义验证消息

如果你需要自定义验证消息,可以在你的模型中放置一个static $messages数组。示例

protected static $messages = [
     'unique' => 'This :attribute is already registered.'
];

基本模型

如果你的所有Eloquent模型都扩展了基本模型,你只需在基本模型中使用这个特性即可。

使用唯一规则更新

当你使用unique规则验证时,如果你想跳过某些id,则只需使用:id:占位符。

让我澄清一下,你不想在用户表中允许重复的电子邮件地址。你在模型中添加此规则

protected static $rules = [
    'email' => 'required|email|unique:users,email'
];

现在有一个用户使用me@example.com注册,该地址尚未在数据库中,这没问题。但现在,如果用户尝试更新其配置文件并进行一些更改,使用相同的电子邮件地址呢?是的,验证将失败。为了解决这个问题,Laravel接受唯一规则的第三个参数。DRYVal使其更加简单,只需将:id:占位符作为第三个参数即可,它就像一个动态的id。示例

protected static $rules = [
    'email' => 'required|email|unique:users,email,:id:'
];

对于此功能,归功于Role Model

ValidationException

DRYVal在验证失败时抛出Dryval\ValidationException异常。你可以像第一个示例中那样在应用级别捕获此异常,或者你可以在控制器/类中捕获它。此异常类的getMessages()(复数)方法将返回验证错误消息(MessageBag),与Laravel的$validator->messages()相同。更多在这里

你还可以在任何需要的地方抛出此异常。

© 2015 Muhammad Usman。MIT许可证。