PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] How to handle validation failed 422 error in vue js on Axios post if user already exist

 February 21, 2022     api, axios, laravel, vue.js     No comments   

Issue

Vue console error log

Am getting this 422 (Unprocessable Entity) error while trying to do a POST request using Laravel and Vue-resource. I currently have the following codes:

register() {
          this.loading = true;          
          this.axios.post('register', {
            firstname: this.firstname,
            lastname: this.lastname,
            email: this.email,
            password: this.password,
            password_confirmation: this.password_confirmation
          })
           .then(response => {
            this.loading = false;
            this.name = '';
            this.email = '';
            this.password = '';
            this.password_confirmation = '';
            this.loginUser(response);
          })
          .catch(err => {
            this.loading = false;            
            if(err.response && err.response.data &&  err.response.data.errors){
              this.errors = err.response.data.errors;
              console.log(err.response.data.errors);
            }
          
          });

        }


Solution

This is a sample of how I handle it in the catch() method

.catch(function(err){
    if(err.response.status == 422) {
        $.each(err.response.data.errors, function(key, value) {
           if(key == 'email'){
               view.emailError = err.response.data.errors.email[0]; //NB: emailError is registered in Vue data 
            }
            if(key == 'password'){
              view.passwordError = err.response.data.errors.password[0]; //NB: passwordError is registered in Vue data 
            }
        });
    }
});

You will need a elements registered in your Vue data to hold the error like I have "emailError" and "passwordError" or you can update the elements directly like $('#emailErrorHolder').text(err.response.data.errors.email[0]);



Answered By - Doro
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing