Code on github https://github.com/kendarorg/Angular101

Validation

These are the main validators present in Angular Forms

Template

Email

Let's try to add the email validator to our function. First we wrap the single address component with a form. On the "blur" event (notice the round brackets that denotes a DOM event)

<form #userForm="ngForm" (blur)="userForm.form.updateValueAndValidity()">
    ...
</form>

Insert the type of field, "email". Notice the addition of the empty "email" attribute the type and the name

<label>Email
  <input 
    email 
    type="email" 
    name="email" 
    [disabled]="readonly" [(ngModel)]="address.email">
</label>

MinLength

I want event that the Address field contains at least 5 chars

<label>Address
  <input minlength="5" name="address" [disabled]="readonly" [(ngModel)]="address.address">
</label>

Finally

Inside the button functions we can then add the form that will be used for the validation. Please notice that "userForm" is the sharp name set inside the form tag attributes.

...
<button mat-icon-button  color="primary" (click)="save(userForm,'/address')" >
...

Controller

Inside the controller we now accept the form. That has the type NgForm, that must be imported

import { NgForm } from "@angular/forms"

Then the save function will change to verify the form validty

save(userForm:NgForm, path:string){
    if(!userForm.form.valid){
        return;
    }

    this.dataService.save(this.address);
    this.readonly=true;
    if(this.addressId==-1){
        this.router.navigateByUrl(path);
    }
}

And the cancel function will reset the value of the data

cancel(path:string){
    this.readonly=true;
    if(this.addressId==-1){
        this.router.navigateByUrl(path);
    }else{
        this.address = this.dataService.getById(this.addressId);
    }
}

Showing errors

Let's add a couple of css classes in the global styles.css

.fieldKo{
    background-color: #ebcacc;
}
.fieldOk{
    background-color: #cdf2cb;
}

Let's take the email field and modify it.

Now changing the email with the wrong value will show an error! The same for the address field. Notice the usage of "addr" instead of "address" this is to avoid naming conflicts with the variable assigned to [(ngModel)]

<label>Address
  <input minlength="5" name="address" [disabled]="readonly" [(ngModel)]="address.address"
    #addr="ngModel"
    [class]="addr.valid || addr.disabled?'fieldOk':'fieldKo'">
</label>

validation


Last modified on: February 17, 2020