I built a contact form using .NET Core 5.0 on the backend and angular 11 on the client-side which allows a user to complete a form from which the data is collected and sent to a static email address.
The issue I am having is handling errors from server to client-side. On the server-side, my model properties use attributes or decorators for validation (Required, StringLength, etc...). I want all server-side errors to render on the client-side, when for example, an empty form is submitted.
HTML
<span class="cross-validation-error-message alert alert-danger"
*ngIf="!contactForm.valid && !hide && contactForm.errors?.value !== ''">{{errorMessage}}
</span>
TypeScript: top portion are relevant properties & below is the api call.
active = false;
submitted = false;
hide = true;
errorMessage!: string;
private postMessage(message: ContactModel) {
this.appService.postMessage(message)
.subscribe(
() => {
if (this.errorMessage == null) {
this.hide = true;
this.submitted = true;
this.active = false;
}
},
(error) => {
console.log(error);
this.hide = false;
this.errorMessage = this.contactForm.errors?.value;
return this.errorMessage.valueOf;
}
);
}
First i suggest you to disable the submit button using angular validators to avoid a network transit with an empty form. No judgement of course. Then i'm not sure to understand all your code, contactForm.errors concern your angular form so is agnostic of your server side so why affect it to this.errorMessage ? Don't you want to display errors like :
this.errorMessage = error; //maybe you have to display each property of error object
this.errorMessage = error.prop1 + ' ' + error.prop2 ...