Custom Validator in Laravel 5

Custom validator in Laravel 5

Try the following:

  1. Make a bind class where you can implement each rule you want extending Validator class.
  2. Make a service provider that extends ServiceProvider.
  3. Add your custom validator provider at config/app.php file.

You can create the bind at Services folder like this:

namespace MyApp\Services;

class Validator extends \Illuminate\Validation\Validator{

public function validateFoo($attribute, $value, $parameters){
return $value == "foo"
}
}

Then, use a service provider to extends the core:

namespace MyApp\Providers;

use MyApp\Services\Validator;
use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider{

public function boot()
{
\Validator::resolver(function($translator, $data, $rules, $messages)
{
return new Validator($translator, $data, $rules, $messages);
});
}

public function register()
{
}
}

Finally, import your service provider at config/app.php like so:

'providers' => [
...
...
'MyApp\Providers\ValidatorServiceProvider';
]

Laravel 5.5 use custom validation rule in validation request file?

Rutvij Kothari answered the question in the comments.

It seems you are validating string with a regular expression, the same logic can be achieved by regex buit-in validation method. Check it out. laravel.com/docs/5.5/validation#rule-regex No need to create your own validation rule. – Rutvij Kothari

If you want to use your validation pass it into an array. like this. 'email' => ['required', 'email', new employeemail]

Laravel 5.5 validate with custom messages

A rewrite and the recommended way of doing it.
Manual for reference https://laravel.com/docs/5.5/validation#creating-form-requests

Use requests files.

  1. run php artisan make:request UpdateUserPasswordRequest
  2. Write the request file

Edit feb 2020: in the latest version of Laravel in the authorize method the global auth() object can be used instead of \Auth so \Auth::check() will become auth()->check(). Both still work and will update if something is removed from the framework

 <?php

namespace App\Http\Requests;

class UpdateUserPasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
// In laravel 8 use Auth::check()
// edit you can now replace this with return auth()->check();
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username' => 'required|max:255',
'oldpassword' => 'required|max:255',
'newpassword' => 'required|min:6|max:255|alpha_num',
'newpasswordagain' => 'required|same:newpassword',
];
}

/**
* Get the validation attributes that apply to the request.
*
* @return array
*/
public function attributes()
{
return [
'username' => trans('userpasschange.username'),
'oldpassword' => trans('userpasschange.oldpassword'),
'newpassword' => trans('userpasschange.newpassword'),
'newpasswordagain' => trans('userpasschange.newpasswordagain'),
];
}

/**
* Get the validation messages that apply to the request.
*
* @return array
*/
public function messages()
{
// use trans instead on Lang
return [
'username.required' => Lang::get('userpasschange.usernamerequired'),
'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
'oldpassword.max' => Lang::get('userpasschange.oldpasswordmax255'),
'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
'newpassword.min' => Lang::get('userpasschange.newpasswordmin6'),
'newpassword.max' => Lang::get('userpasschange.newpasswordmax255'),
'newpassword.alpha_num' =>Lang::get('userpasschange.newpasswordalpha_num'),
'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
'username.max' => 'The :attribute field must have under 255 chars',
];
}

  1. In UserController
<?php namespace App\Http\Controllers;

// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\UpdateUserPasswordRequest as ChangePassRequest;
//etc

class UserCrudController extends Controller
{
public function chnagePassword(ChangePassRequest $request)
{
// save new pass since it passed validation if we got here
}
}

make custom validation in laravel

$this->validate($request,[
'name'=>['required',Rule::unique('brands')->where('deleted_at',1)],
]);

Note : please import Rule at top.

How to update existing current name ?

Code Below :

public function update(Request $request, $id)
{
$this->validate($request,[
'name'=>['required',Rule::unique('brands')->ignore($id)],
]);
}

Laravel 5 - where to place reusable custom validator?

Definitely extend the validator in a Service Provider. You can use the existing app/Providers/AppServiceProvider.php or create another one just for validation.

Then, in the boot() method, add this:

public function boot(){
$this->app['validator']->extend('min_image_size', function($attribute, $value, $parameters) {
$imageSize = getimagesize($value->getPathname());
return ($imageSize[0] >= $parameters[0] && $imageSize[1] >= $parameters[1]);
});
}

It might also be worth putting the actual validation rules in a separate class and using this syntax:

$this->app['validator']->extend('min_image_size', 'MyCustomValidator@validateMinImageSize');

Laravel 5.0 Custom Validation Method not Found

Looks like your custom rule isn't getting registered and laravel is defaulting to find the method in it's base class. Try running php artisan clear-compiled. Also you can use use Input; and use Validator; since they have facades registered.

How add Custom Validation Rules when using Form Request Validation in Laravel 5

Using Validator::extend() like you do is actually perfectly fine you just need to put that in a Service Provider like this:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider {

public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}

public function register()
{
//
}
}

Then register the provider by adding it to the list in config/app.php:

'providers' => [
// Other Service Providers

'App\Providers\ValidatorServiceProvider',
],

You now can use the numericarray validation rule everywhere you want

Custom Laravel validation messages

If you use $this->validate() simplest one, then you should write code something like this..

$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:250',
];

$customMessages = [
'required' => 'The :attribute field is required.'
];

$this->validate($request, $rules, $customMessages);


Related Topics



Leave a reply



Submit