Implementing form validation

Angular provides useful validation-related techniques, one of which works by using standard HTML validation attributes.

Inspecting the REST API, we can see that the following fields' validation rules should be met:

  • title: Required, minlength="3", maxlength="50"
  • category: Required

Let's add the necessary HTML attributes to product-form.component.html to reflect these validation rules:

...
<input id="title" name="title" [(ngModel)]="product.title"
required minlength="3" maxlength="50" />
...
<select id="category" name="category"
[(ngModel)]="product.category" required>
<option value=''>Select category..</option>
<option *ngFor="let c of categories" [value]="c.name">{{ c.name }}</option>
</select>
...

Luckily, Angular tracks element-specific and form-wide states. Specifically, ngModel toggles the following class names on every element, according to its state:

  • ng-touched / ng-untouched: Represents whether the element was visited at least once or not by the user
  • ng-dirty / ng-pristine: Represents whether the element's value was changed or not
  • ng-valid / ng-invalid: Represents whether the element's value is valid or not

To reflect elements' invalid status, add the following CSS to the product-form.component.css file:


.ng-invalid:not(form) {
border-left: 5px solid #a94442;
}

You can now run the app, and you should see a red border visible when the elements' Title and Category fields are invalid.

Furthermore, you can use Angular's form-state monitoring to control the HTML DOM. Let's add feedback to the user, indicating error messages and disabling the submit button until the form is valid.

To do so, let's use another feature of Angular: element references.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225