1

I am trying to print out custom error messages based on the error received in JSON response after using Fetch API.

This is the error message I'm getting after trying to submit data with email that is already in the database:

{"message":"Invalid Request","messages":{"email":["validation.unique"]}}

Here is another error saying email is simply not valid:

{"message":"Invalid Request","messages":{"email":["validation.email"]}}

And I'm trying to print a specific error to the user to say that the email is already in use. I need something like this.

try {
  ...
} catch(error) {
  if(error.message == "validation.unique") {
  ... print error saying email already in use ...
  } elseif(error.message == "validation.email") {
  ... print error saying email is not valid ...
  }
}

How do I check a JSON response in the if statement? The server that's sending the response is using Laravel.

3
  • What do you have in error? Commented Feb 25, 2021 at 8:43
  • It's a json response: {"message":"Invalid Request","messages":{"email":["validation.unique"]}} Commented Feb 25, 2021 at 8:52
  • and your code is not working? Commented Feb 25, 2021 at 10:55

1 Answer 1

2

I think you can use 'JSON.parse()'.

function test(tmpJson) {
    var tmpArr = JSON.parse(tmpJson);
    if (tmpArr.message == "Invalid Request") {
        var tmpE = tmpArr.messages.email;
        if (tmpE == "validation.unique") {
            alert('email already in use');
        } else if (tmpE == "validation.email") {
            alert('email is not valid');
        }
    } else {
        //success
    }
}

var testJson = '{"message":"Invalid Request","messages":{"email":["validation.unique"]}}';

test(testJson);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.