Home > Software engineering >  How to add custom form validation in Laravel?
How to add custom form validation in Laravel?

Time:08-16

I am trying to add custom validation in my controller.

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;

class MyController extends Controller
{

    public function __contruct()
    {
    }

    public function store(Request $req)
    {

        $v = Validator::make($req->all(), [
          'contract_ref' => 'required'
        ]);

        $v->after(function($v) use(&$req){
            dd('custom validations');

            // list of custom validations
            if ($req->div_id == '') {
                $validator->errors()->add('div_id', 'Please select a Division');
            };
        });

        dd('NO!');

        if ($v->fails()) {
         //
        }

        $v->validate();
    }

}

However, for some reason I don't understand. Nothing in the -after closure is being done. In example above, I get "NO!" dumped instead of the expected "custom validations"

This ->after has worked for me previously and I don't get why it is not working here.

CodePudding user response:

I reccomend using Closures https://laravel.com/docs/8.x/validation#using-closures as it can keep all of your validation logic in one place

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
  'title' => [
    'required',
    'max:255',
    function ($attribute, $value, $fail) {
        if ($value === 'foo') {
            $fail('The '.$attribute.' is invalid.');
        }
    },
  ],
]);

CodePudding user response:

Your are requesting dd('NO!') before the actual validate

try this :

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;

class MyController extends Controller
{

    public function __contruct()
    {
    }

    public function store(Request $req)
    {

        $v = Validator::make($req->all(), [
            'contract_ref' => 'required'
        ]);

        $v->after(function ($v) use (&$req) {
            dd('custom validations');

            // list of custom validations
            if ($req->div_id == '') {
                $validator->errors()->add('div_id', 'Please select a Division');
            };
        });


        if ($v->fails()) {
            //
        }

        $v->validate();
        dd('NO!');
    }
}

CodePudding user response:

Have you used that?

$v->validate();

Below is an example of validation. You can also check your invalid input values inside fail check.

        $validation_array = [
            'id' => 'required',
            'date' => 'required|date',
            'material_type' => 'required',
            'fabric' => 'required_if:material_type,==,0',
            'color' => 'required_if:material_type,==,1',
            'quantity' => 'required|numeric',
            'unit' => 'required',
        ];

        $validation_messages_array = [
            'fabric.required'    => 'The fabric field is required when material type is fabric.',
            'color.required_if' => 'The color field is required when material type is blind.'
        ];

        $validator = Validator::make(
            $request->all(),
            $validation_array,
            $validation_messages_array
        );

        $validator->after(function ($validator) {
        });

        if ($validator->fails()) {
            //code if not valid
        }

        $validator->validate();
  • Related