Search code examples
laravelangularangular2-formsangular2-services

Handle Server Side Laravel Validation with Angular2


I have started using Angular2 recently with laravel API's. but I don't know how to handle server side validation with Angular2.

I'm returning this response from server side.

`{"success":false,
"code":422,
"error":[],
"message":
{
"name":["The name field is required."],
"email":["The email field is required."]
}
}`

Can anyone please help me out here?


Solution

  • Get instance ofform in @Component, then set .errors object. Something like:

    save(data: any){
        this.http.post(data).subscribe((response) => this.handleSuccess(response),
        (errorResponse) => {
            if(errorResponse.status !== 422){
                this.handleHttpError(errorResponse);
            }else{
                let data = errorResponse.json();
                Object.keys(data).forEach((fieldName) => {
                    this.form.controls[fieldName].setErrors({backend: data[fieldName]});
                });
            }
        });
    }