adeelmahmood
adeelmahmood

Reputation: 2431

Server side validation for angular 2 forms

I am trying to figure out how I can send some data to a server side API call, let that do the validation and then return back with some validation errors and those validation errors should be displayed along with the component that caused the validation error. Here is how my data model looks like:

export class Order {
   orderNo: string;
   items: Item[];

   constructor() {
      this.items = [];
   }
}

export class Item {
    recNo: string;
}

This is how the HTML form looks like

<div class="form-group">
    <label name="orderNo">Order Number</label>
    <input type="text" formControlName="orderNo" />
</div>

<div formArrayName="items">
    <div *ngFor="let item of orderForm.controls.items.controls; let i=index" [formGroupName]="i">
         <div class="form-group">
            <label>Item # {{i}}</label>
            <input type="text" formControlName="recNo" />
         </div>
    </div>
</div>

The validation errors that I receive from the server are in this form

[
  {
    "field": "orderNo",
    "message": "order number is required"
  },
  {
    "field": "items[2].recNo",
    "message": "record number is required"
  }
]

I am not able to figure out how, once I receive the validation errors, can I update the errors objects on the form controls or populate some other structure to show the errors. Its a bit simpler for static fields like orderNo but a lot more complex for nested array fields like items[0].recNo to update the errors programmatically. Any ideas would be appreciated.

Upvotes: 1

Views: 1944

Answers (1)

adeelmahmood
adeelmahmood

Reputation: 2431

This is what I ended up doing:

<div class="form-group" [class.has-danger]="!ctrl.valid && ctrl.enabled">
     <input type="text" class="form-control" [formControl]="ctrl" 
         value="{{valueFormatter(ctrl)}}"
         [class.form-control-danger]="!ctrl.valid && ctrl.enabled"
         [ngbTooltip]="ctrl.errors ? ctrl.errors.e : falsy" />
</div>

Basically, setting up error classes on the form control based on the ctrl valid/error state and here is an example of specifying an error on a control:

this.ctrl.setErrors({ "e": this.label + " is required"});

I just used a predefined error key e to display any errors. This way, once I receive the error list from the backend, I can set the e error on a control and have that show up in a tooltip on the control.

Upvotes: 1

Related Questions