semantic-lab/lara-validator

A Laravel artisan command expansion for developer more convenient generate FormRequest with validation rules by JSON file

v1.0 2019-09-11 08:03 UTC

This package is not auto-updated.

Last update: 2024-10-31 10:13:35 UTC


README

semantic-lab/lara-validator-test is an Laravel php artisan plugin for easily convert JSON file into Laravel FormRequest.

Usage

Via composer:

composer require semantic-lab/lara-validator --dev

Or add the package to your dependencies in composer.json and run composer update on the command line to download the package:

{
    "require-dev": {
        "lara-validator": "1.0"
    }
}

Commands

make

This command will generate Laravel FormRequest with rules configs(JSON files) those under the {project}/config/validators/ (read more for rules config setting).

php artisan validator:make

After execute the command, by default, the FormRequest will be generated at {project}/app/Http/Requests/, then you can use the FormRequest in controller to validate the request.

<?php

use App\Http\Requests\Login;

class UserController extends Controller
{
    public function login(Login $request) {
        // ...
    }
}

:make

Rule Config

Rule config is an JSON file with request rules under the {project}/config/validators/. These configs not only to generate FormRequest for backend, also useful for frontend to validate data before passing to backend for double check (read more for JavaScript validation).

{
  "validators": {}
}

The example on above, is the format of rule config, you can set multiple validators under the "validators". Each validator will generate a FormRequest.

In example, it will generates "Login" and "Register" two FormRequest by the rule config show as below.

{
  "validators": {
    "Login": {
      "body": {}
    },
    "Register": {
      "body": {}
    }
  }
}

Simple setting

If the request is simple, the fields to validate has no nested rules or array rules to set, most of the rule settings are same as Laravel original validation settings.

To start our rules setting, note that, all the rules should be set under the property "body".

Default Error Message

With Laravel default message, you can set as below:

{
  "validators": {
    "Login": {
      "body": {
        "email": "required|string|email",
        "password": "required|string|min:6"
      }
    }
  }
}
Custom Error Message

If you need the custom error message for special rules, just set the rules under the property "rules".

{
  "validators": {
    "Login": {
      "body": {
        "email": "required|string|email",
        "password": {
          "rules": {
            "required": null,
            "string": null,
            "min:6": "The field 'password' can not be less then :min characters."
          }
        }
      }
    }
  }
}

The example on above, rule "required" and "string" under the field "password" will using default error message by setting null, and rule "min:6" has customize error message.

Complex setting

If the value of field to validate is an array or there is nested field to validation, please follow below setting.

Nested Rules Setting

To set the nested field, just set as nested object.

{
  "validators": {
    "CreateGroup": {
      "body": {
        "id": "required|string",
        "token": "required|string",
        "group": {
          "isPrivate": "boolean",
          "groupName": "required|string",
          "startDate": "present|date",
          "frequency": "present|in:1,30,90",
          "endDate": "present|date"
        }
      }
    }
  }
}

The example on above, we can set the rules for sub-fields of "group".

Array Rules Setting

For valid all sub-fields in an array field, please set an example in the array value.

{
  "validators": {
    "CreateUsers": {
      "body": {
        "users": [
          {
            "name": "required|string|min:4",
            "email": "required|email",
            "password": "required|string|min:6|regex:/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?]).*$/i|confirmed",
            "phone": "required|regex:/^(09)[0-9]{8}$/gi|bail",
            "gender": "nullable|numeric|in:0,1,2",
            "address": "present|string"
          }
        ]
      }
    }
  }
}

Including to the example, it is a rule of api which register several user at once. Because all the users have same fields that should be validated, we only need to set once in the array value.

Advanced

Fail Response

Laravel default redirect URL while request is invalid, in our rule config, also support several different types of fail response.

We can set default fail response for all validators in same rule config, and customize for specific validator.

{
  "validators": {
    "Login": {
      "body": {},
      "failResponse": {
        "type": "exception"
      }
    },
    "CreateUsers": {
      "body": {}
    }
  },
  "failResponse": {
    "type": "ignore"
  }
}

The example on above, "Login" validator has customize fail response as "exception", and the validator "CreateUsers" without setting the fail response will using "ignore" which set as default fail response at first layer.

The available fail response types:

typecomment
defaultredirect to "/"
ignorestill pass throw controller function(action)
exceptionthe response will return \Illuminate\Support\MessageBag in JSON format
responsethe response will return given Response Class in JSON format
Default

If default using "default type" of response for all validators in same rule config, there is no need to setting, in other cases, set property "failResponse" as below.

{
  "failResponse": {
    "type": "default"
  }
}
Ignore

Sometimes we need to pass into the controller function for more process even the request is invalid, we can set property "failResponse" as "ignore".

{
  "failResponse": {
    "type": "ignore"
  }
}
Exception

To return MessageBag in JSON format as response, set property "failResponse" as below.

{
  "failResponse": {
    "type": "exception",
    "httpStatus": 200
  }
}

There is an optional property "httpStatus" for setting the HTTP status of response, Laravel default as 422.

Response

If we want return the response while request is invalid, however in special JSON structure, we can set property "failResponse" as "response".

{
  "failResponse": {
    "type": "response",
    "class": "manager\LoginResponse",
    "httpStatus": 200
  }
}

The optional properties defined as below:

propertycomment
classthe sub-path of response class under the {project}/app/Http/Response/
httpStatusthe HTTP status of response

In example, we create a Response class which implement App\Http\Responses\IValidatorResponse at first,

<?php
namespace App\Http\Responses\manager;

use App\Http\Responses\IValidatorResponse;

class LoginResponse implements IValidatorResponse
{
    public function setValidationError($error){
        // TODO: Implement setValidationError() method.
    }
    
    public function toJSONResponse($httpStatus = 422){
        // TODO: Implement toJSONResponse() method.
    }
}

than we set the rule config.

{
  "validators": {
    "Login": {
      "body": {},
      "failResponse": {
        "type": "response",
        "class": "manager\LoginResponse",
        "httpStatus": 200
      }
    },
    "CreateUsers": {
      "body": {}
    }
  }
}