I'm looking for solution on how I can display errors that the server respond, this is the respond for every invalid submission so I want to make the error handler in the app level and not in a controller.
I want to display the errors both on the FORM level and on the field level.
I have a REST API that in case of error return the following JSON object:
{
"message": "Validation error: Validation notEmpty failed,\nValidation error: Validation isEmail failed",
"errors": [
{
"field": "username",
"message": "Validation notEmpty failed"
},
{
"field": "email",
"message": "Validation isEmail failed"
}
]
}
How can I create a service that display the errors in case there is any?
Thanks
So, i created this for another answer. Let me know if this sort of a setup works for you. Here, the error is intended to be displayed on response from the server after button click. You can modify it accordingly.
I have given the field a custom template as follows:
formlyConfigProvider.setWrapper({
name: 'inputWrapper',
template: '<div ng-class="to.changeColor==\'red\'? \'redBorder\' : \'otherBorder\'"><formly-transclude></formly-transclude>{{to.keyVal}}</div>'
});
The form elements are defined through a schema format to allow each element to be individually accessed.
vm.schema={
"schema": {
"coolValue" : [{
"key": "coolValue",
"type": "input",
"wrapper": ['inputWrapper'],
"templateOptions": {
"type" : "text",
"label": 'Cool Value',
"keyVal":"",
"changeColor":"green"
}
}]
}
};
Finally, the onSubmit
function
function onSubmit() {
//Do whatever you want here
//Let's say your server returns an error "iNVALID Credentials"
var response={
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
};
vm.schema.schema.coolValue[0].templateOptions.changeColor="red";
vm.schema.schema.coolValue[0].templateOptions.keyVal=response.error.message;
}
});
You can essentially pass any error message or response from the server here.
The CSS contains a class to add a red border
to the field.You are free to disable this.Feel free to ping if you need anything in this area as well.
Here is a DEMO