Last active
August 29, 2015 14:20
-
-
Save gjinali/e0d282a29173341c5bd0 to your computer and use it in GitHub Desktop.
Laravel 5 JSON Validation Rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Services; | |
use Illuminate\Validation\Validator; | |
class JsonValidation extends Validator{ | |
private $_customMessages = array( | |
"json" => "The :attribute attribute is not valid JSON.", | |
); | |
public function __construct( $translator, $data, $rules, $messages = array(), $customAttributes = array() ) { | |
parent::__construct( $translator, $data, $rules, $messages, $customAttributes ); | |
$this->setCustomMessages($this->_customMessages); | |
} | |
/** | |
* Allow valid json string | |
* @param $attribute | |
* @param $value | |
* @param $parameters | |
* @return bool | |
*/ | |
public function validateJson($attribute, $value, $parameters) | |
{ | |
json_decode($value); | |
return (json_last_error() == JSON_ERROR_NONE) ? true : false; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Providers; | |
use App\Services\JsonValidation; | |
use Illuminate\Support\ServiceProvider; | |
use Validator; | |
class JsonValidationServiceProvider extends ServiceProvider{ | |
public function register(){} | |
public function boot() | |
{ | |
Validator::resolver(function($translator, $data, $rules, $messages) | |
{ | |
return new JsonValidation($translator, $data, $rules, $messages); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Laravel 5 Json Validation Rule
Laravel provides many useful and generic validation rules. But what if we want more? What if we need something more specific for example if we need validation for a valid json string from inputs?
We can use this JsonValidation class wich extends Laravel base Validation class.
Installation:
Copy JsonValidation.php file in App\Services folder.
Copy JsonValidationServiceProvider.php file in App\Provider folder.
Register provider in config\app.php $providers array:
'App\Providers\JsonValidationServiceProvider',
Usage:
In your validation rules you can use 'json' rule ex:
$rules = [ 'your_input' => 'json' ];