-1

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;
           
 }
 );
 }

1 Answers1

0

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 ...
Mulholland
  • 33
  • 4
  • for the button, i mean : – Mulholland Aug 26 '21 at 15:21
  • No worries, Mulholland. I get what you are saying, add this *ngIf=!contactForm.valid to the button tag to prevent form submission unless no errors exist. Yes, that is how I would like the errors to display however due to the parameters I have been given as the developer it is necessary, for this use-case, to show all validation errors on submit; including the error handling of API responses returned with a status other than 200, 201 or 204. – pokerkid100717 Aug 26 '21 at 15:25
  • thanks! for internal server error would the same principle apply? **this.errorMessage = error.StatusCode500 + ' '** To do this, I can define a string named statusError500 that says 'please attempt your submission again, we ran into a problem getting your submission' (language needs works). – pokerkid100717 Aug 26 '21 at 15:50
  • This is spot on and works correctly: (this.errorMessage = error; ) 'maybe you have to display each property of error object' -- that is when I realized what the issue is for this use-case. I am getting back all the error object info but need to parse it and render error.message (applicable error) when a 500 is returned. Advice? – pokerkid100717 Aug 26 '21 at 18:31