Reputation: 513
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.
Upvotes: 1
Views: 871
Reputation: 695
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);
Upvotes: 2