Axios to catch custom validation rule error message?

Published 1 week ago by sanuglia

Using Laravel 5.4, I've set up a custom validation rule:

class AppServiceProvider extends ServiceProvider
{
    
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        // Custom validators
        Validator::extend(
            'greater_than_field', function ( $attribute, $value, $parameters, $validator ) {
            $min_field = $parameters[ 0 ];
            $data      = $validator->getData();
            $min_value = $data[ $min_field ];
            
            return $value > $min_value;
        } );
        
        Validator::replacer(
            'greater_than_field', function ( $message, $attribute, $rule, $parameters ) {
            return str_replace( ':field', $parameters[ 0 ], $message );
        } );
    ...

And I have a Form Request class:

class ClientAttachBusinessRequest extends FormRequest
{
        
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return TRUE;
    }
    
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'businessName' => 'required',
            'fromDate'     => 'sometimes|nullable|date',
            'toDate'       => 'sometimes|nullable|date|greater_than_field:fromDate',
        ];
    }
    
    
    public function messages()
    {
        return [
            'businessName.required' => 'Nyet.',
            'toDate.greater_than_field' => 'The TO date must come AFTER the FROM date',
        ];
    }
}

If I submit a form with an invalid toDate "normally", the $errors is populated, and I'm able to display the message in my view using {{ $errors->first('toDate') }}.

Now use ajax/axios:

If I submit a form with an empty string for the businessName, I do get an HTTP 422 response with the contents of:

{"businessName":["Nyet."]}

If I submit a form with an empty string for the toDate, I do NOT get an HTTP 422 response. Instead, my controller continues processing as if nothing was invalidated.

Is this a feature? a bug? My goal here is to return an error message to the axios POST.

d3xt3r
d3xt3r
1 week ago (145,880 XP)

You have marked toDate as sometimes. Validation will only trigger if present...

sanuglia

Oh, yes, I neglected to say that I do include the 'toDate' when testing so that sometimes does trigger.

sanuglia

Orrrr,...maybe not. I just noticed that those fields aren't being passed to the controller. Thanks for pointing me that way! I can take it from here.

sanuglia

Wellllll,....now that I've fixed the js to send the toDate values correctly, the validation now fails correctly when the toDate is less than fromDate.

But instead of returning a 422 with JSON of the message, the page gets redirected (refreshed).

Might anyone have an idea of why it's not returning a JSON with error message instead?

sanuglia

Indeed, when I have a custom rule as defined in my AppServiceProvider (as above), and the validation of such rule fails, it appears that Laravel DOES generate a redirect response instead of generating a JSON response containing all of the validation errors when using AJAX.

Has anyone else experienced this?

Sign In or create a forum account to participate in this discussion.