Skip to content

Instantly share code, notes, and snippets.

@gjinali
Last active August 29, 2015 14:20
Show Gist options
  • Save gjinali/e0d282a29173341c5bd0 to your computer and use it in GitHub Desktop.
Save gjinali/e0d282a29173341c5bd0 to your computer and use it in GitHub Desktop.
Laravel 5 JSON Validation Rule
<?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;
}
}
<?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);
});
}
}
@gjinali
Copy link
Author

gjinali commented May 6, 2015

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' ];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment