cals/validator

A simple encapsulation of Illuminate\Contracts\Validation\Factory in Laravel.

v1.0.1 2018-07-04 03:18 UTC

This package is not auto-updated.

Last update: 2024-09-19 05:20:11 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Validator is designed for Laravel when use ajax. Validator is a simple encapsulation of Illuminate\Contracts\Validation\Factory in Laravel, which excepted validating data easier.

Install

You can simply install Validator use composer.

composer require cals/validator

And then add the Cals\Validator\ValidatorServiceProvider::class to your config/app.php providers array.

Cals\Validator\ValidatorServiceProvider::class

If you use Laravel 5.5 and after, you don't need do it cause laravel will auto load the provider.

Configuration

You have to publish the config using this command:

php artisan vendor:publish --tag="validator"

You should put your rules and messages in it.

Usage

Validator provides a simple way to validate data, you can simply use it anywhere you want.

validate(array $values = [], $resource, array $messages = [], $sometimes = false)

$values is the data you wish to validate, $resource is one of your key in rules which contained in validator.php. And you can set messages while validating fails to return by using $message.When $sometimes was true, rules in sometimes would be used.

When validate failed, Validator will send a json response automatically.The returned data is like this.

{
    "errors": {
        "username": [
            "用户名不能为空"
        ],
        "password": [
            "密码不能是字母、数字、破折号和下划线之外的其他字符",
            "密码必须在 6 到 18 位之间"
        ]
    }
}

Example

Validator suggest using like this.

<?php

namespace App\Http\Controllers;

use Cals\Validator\AjaxValidator;
use Illuminate\Http\Request;

class ExampleController extends Controller
{
    private $validator;
    
    public function __construct(AjaxValidator $validator)
    {
        $this->validator = $validator;
    }

    public function index(Request $request)
    {
        $values = $request->all();
        $this->validator->validate($values,'user');
    }
}

License

The Validator is open-sourced library licensed under the MIT license.