Validation Of Model-Based Form In Angular

Validation of an Angular form is very tricky. The validation is done in the code rather than with a template. This is a highly scalable approach.  I am going to demonstrate an example  using typescript.

Product class has three properties: Name, Category, and Price.

Product.ts

  1. exportclass Product {  
  2.     constructor(public id ? : number, public name ? : string, public category ? : string, public price ? : number) {}  
  3. }  

To enable model-based validation requires a new dependency to be declared in the application app.module.ts, as highlighted below, classed needs to be imported

  1. import { NgModule } from"@angular/core";  
  2. import { FormsModule } from"@angular/forms";  
  3. import { BrowserModule } from"@angular/platform-browser";  
  4. import { ProductComponent } from"./component";  
  5. import { ReactiveFormsModule } from"@angular/forms";  
  6. @NgModule({  
  7.    declarations: [ProductComponent,],  
  8.    imports: [FormsModule, BrowserModule, ReactiveFormsModule],  
  9.    bootstrap: [ProductComponent]  
  10. })  
  11. exportclass AppModule { }  

A new Class Form.model is defined to handle the form validation to keep the template simple. It does make sense to handle as much of the form as possible in the model and minimize the complexity of the form.

Form.model.ts

  1. import {  
  2.     FormControl,  
  3.     FormGroup,  
  4.     Validators  
  5. } from "@angular/forms";  
  6. exportclass ProductFormControl extends FormControl {  
  7.     label: string;  
  8.     modelProperty: string;  
  9.     constructor(label: string, property: string, value: any, validators: any) {  
  10.         super(value, validators);  
  11.         this.label = label;  
  12.         this.modelProperty = property;  
  13.     }  
  14.     getValidationMessages() {  
  15.         let message: string[] = [];  
  16.         if (this.errors) {  
  17.             for (let errorName inthis.errors) {  
  18.                 switch (errorName) {  
  19.                     case "required":  
  20.                         message.push(`You must enter a ${this.label}`);  
  21.                         break;  
  22.                     case "minlength":  
  23.                         message.push(`A ${this.label} must be at least ${this.errors['minlength'].requiredLength}`);  
  24.                         break;  
  25.                     case "pattern":  
  26.                         message.push(`The ${this.label} contains illegal characters`);  
  27.                         break;  
  28.                     case "maxlength":  
  29.                         message.push(`A ${this.label} must be no more than ${this.errors['maxlength'].requiredLength} charaters`);  
  30.                         break;  
  31.                 }  
  32.             }  
  33.         }  
  34.         return message;  
  35.     }  
  36. }  
  37. exportclass ProductFormGroup extends FormGroup {  
  38.     constructor() {  
  39.         super({  
  40.             name: new ProductFormControl("Name""name"" ", Validators.required),  
  41.             price: new ProductFormControl("Price""price""", Validators.compose([Validators.required,  
  42.                 Validators.pattern("^[0-9\.]+$")  
  43.             ])),  
  44.             category: new ProductFormControl("Category""category""", Validators.compose([Validators.required,  
  45.                 Validators.pattern("^[A-Za-z ]+$"),  
  46.                 Validators.minLength(3),  
  47.                 Validators.maxLength(10)  
  48.             ]))  
  49.         });  
  50.     }  
  51.     get productControls(): ProductFormControl[] {  
  52.         return Object.keys(this.controls).map(k => this.controls[k] as ProductFormControl);  
  53.     }  
  54.     getFormValidationMessage(form: any) {  
  55.         let message: string[] = [];  
  56.         this.productControls.forEach(k => {  
  57.             k.getValidationMessages().forEach(m => message.push(m))  
  58.         });  
  59.         return message;  
  60.     }  
  61. }  

Now I have the form model class to handle the validation, and now I can use this class in my component.

Component.ts

  1. import {  
  2.     ApplicationRef,  
  3.     Component  
  4. } from "@angular/core";  
  5. import {  
  6.     NgForm  
  7. } from "@angular/forms";  
  8. import {  
  9.     Model  
  10. } from "./repository";  
  11. import {  
  12.     Product  
  13. } from "./product";  
  14. import {  
  15.     ProductFormGroup  
  16. } from "./form.model";  
  17. @Component({  
  18.     selector: "app",  
  19.     templateUrl: "app/template.html"  
  20. })  
  21. exportclass ProductComponent {  
  22.     model: Model = new Model();  
  23.     form: ProductFormGroup = new ProductFormGroup();  
  24.     constructor(ref: ApplicationRef) {  
  25.         ( < any > Window).appRef = ref;  
  26.         ( < any > Window).model = this.model;  
  27.     }  
  28.     getProductByPosition(position: number) {  
  29.         returnthis.model.getProdcts()[position];  
  30.     }  
  31.     getClassByPosition(position: number) {  
  32.         let product = this.getProductByPosition(position);  
  33.         return "p-a-1 " + (product.price < 50 ? "bg-info" : "bg-warning");  
  34.     }  
  35.     getClass(): string {  
  36.         return (this.model.getProdcts()).length == 5 ? "bg-success" : "bg-info";  
  37.     }  
  38.     getClassesByKey(key: number): string {  
  39.         let product = this.model.getProducts(key);  
  40.         return "p-a-1 " + (product.price < 50 ? "bg-info" : "bg-success");  
  41.     }  
  42.     getClassMap(key: number): object {  
  43.         let product = this.model.getProducts(key);  
  44.         return {  
  45.             "text-xs-center bg-danger": product.name == "Kayak",  
  46.             "bg-info": product.price < 50  
  47.         };  
  48.     }  
  49.     fontsizewithUnits: string = "30px";  
  50.     fontsizewithoutUnits: string = "30";  
  51.     getStyle(key: number): object {  
  52.         let product = this.model.getProducts(key);  
  53.         return {  
  54.             fontSize: "20px",  
  55.             "margin.px": 100,  
  56.             color: product.price > 50 ? "red" : "green"  
  57.         };  
  58.     }  
  59.     getProduct(key: number): Product {  
  60.         returnthis.model.getProducts(key);  
  61.     }  
  62.     getProducts(): Product[] {  
  63.         returnthis.model.getProdcts();  
  64.     }  
  65.     getProductNumber(): number {  
  66.         console.log("getProducts number is invoked");  
  67.         returnthis.model.getProdcts().length;  
  68.     }  
  69.     getRoundedPrice(key: number): number {  
  70.         return Math.floor(this.model.getProducts(key).price);  
  71.     }  
  72.     getSelected(product: Product): boolean {  
  73.         return product.name == this.selectedProduct;  
  74.     }  
  75.     targetName: string = "Kayak";  
  76.     counter: number = 1;  
  77.     selectedProduct: string;  
  78.     newproduct: Product = new Product();  
  79.     get jsonProduct() {  
  80.         return JSON.stringify(this.newproduct);  
  81.     }  
  82.     addProduct(p: Product) {  
  83.         console.log("New Product " + this.jsonProduct);  
  84.     }  
  85.     formSubmitted: boolean = false;  
  86.     submitForm(form: NgForm) {  
  87.         this.formSubmitted = true;  
  88.         if (form.valid) {  
  89.             this.addProduct(this.newproduct);  
  90.             this.newproduct = new Product();  
  91.             form.reset();  
  92.             this.formSubmitted = false;  
  93.         }  
  94.     }  
  95. }  

I have imported the ProductFormGroup class from the form.model module and used it to define a property called form, which I customize for use in the template.

Template.html

  1. <style>  
  2.     input.ng-dirty.ng-invalid {  
  3.         border: 2pxsolid#ff0000  
  4.     }  
  5.   
  6.     input.ng-dirty.ng-valid {  
  7.         border: 2pxsolid#6bc502  
  8.     }  
  9. </style>  
  10. <divclass="bg-info p-a-1 m-b-1"> Model Data: {{jsonProduct}}</div>  
  11.     <formnovalidate[formGroup]="form" (ngSubmit)="submitForm(form)">  
  12.         <divclass="bg-danger p-a-1 m-b-1" *ngIf="formSubmitted && form.invalid"> There are problem with the form  
  13.             <ul>  
  14.                 <li*ngFor="let error of form.getFormValidationMessage()">{{error}}</li>  
  15.             </ul>  
  16.             </div>  
  17.             <divclass="form-group"> <label>Name</label>  
  18.                 <inputclass="form-control" formControlName="name" name="name" [(ngModel)]="newproduct.name" />  
  19.                 <ulclass="text-danger list-unstyled" *ngIf="(formSubmitted || form.controls['name'].dirty) && form.controls['name'].invalid">  
  20.                     <li*ngFor="let error of form.controls['name'].getValidationMessages()">{{error}}</li>  
  21.                         </ul>  
  22.                         </div>  
  23.                         <divclass="form-group"> <label>Category</label>  
  24.                             <inputclass="form-control" formControlName="category" name="category" [(ngModel)]="newproduct.category" />  
  25.                             <ulclass="text-danger list-unstyled" *ngIf="(formSubmitted || form.controls['category'].dirty) && form.controls['category'].invalid">  
  26.                                 <li*ngFor="let error of form.controls['category'].getValidationMessages()">{{error}}</li>  
  27.                                     </ul>  
  28.                                     </div>  
  29.                        <divclass="form-group"> <label>Price</label>  
  30.                     <inputclass="form-control" name="price" formControlName="price" [(ngModel)]="newproduct.price" />  
  31.                   <ulclass="text-danger list-unstyled" *ngIf="(formSubmitted || form.controls['price'].dirty) && form.controls['price'].invalid">  
  32.          <li*ngFor="let error of form.controls['price'].getValidationMessages()">{{error}}</li>  
  33.         </ul>  
  34.      </div>  
  35.  </form>  
ASP.NET 

How to add a custom Validation on angular form.

In the previous blog I have shown model based validation on a form. I'm continuing that now if you want to add a custom validation on a form.

First you need to create a custom validation class.

Limit.Validators.ts

  1. import {  
  2.     FormControl  
  3. } from "@angular/forms";  
  4. exportclass LimitValidators {  
  5.     static Limit(limit: number) {  
  6.         return (control: FormControl): {  
  7.             [key: string]: any  
  8.         } => {  
  9.             let val = Number(control.value);  
  10.             if (val != NaN && val > limit) return {  
  11.                 "limit": limit,  
  12.                 "actualValue": val  
  13.             };  
  14.             else returnnull;  
  15.         }  
  16.     }  
  17. }  

As I have shown you earlier from.model class is handling all of the stuff related to form validation. To keep the  template simple you add the below highlighted code to that class.

  1. import {  
  2.     FormControl,  
  3.     FormGroup,  
  4.     Validators  
  5. } from "@angular/forms";  
  6. import {  
  7.     LimitValidators  
  8. } from "./limit.formvalidators";  
  9. exportclass ProductFormControl extends FormControl {  
  10.     label: string;  
  11.     modelProperty: string;  
  12.     constructor(label: string, property: string, value: any, validators: any) {  
  13.         super(value, validators);  
  14.         this.label = label;  
  15.         this.modelProperty = property;  
  16.     }  
  17.     getValidationMessages() {  
  18.         let message: string[] = [];  
  19.         if (this.errors) {  
  20.             for (let errorName inthis.errors) {  
  21.                 switch (errorName) {  
  22.                     case "required":  
  23.                         message.push(`You must enter a ${this.label}`);  
  24.                         break;  
  25.                     case "minlength":  
  26.                         message.push(`A ${this.label} must be at least ${this.errors['minlength'].requiredLength}`);  
  27.                         break;  
  28.                     case "limit":  
  29.                         message.push(`A ${this.label} can not be more than ${this.errors['limit']}`);  
  30.                         break;  
  31.                     case "pattern":  
  32.                         message.push(`The ${this.label} contains illegal characters`);  
  33.                         break;  
  34.                     case "maxlength":  
  35.                         message.push(`A ${this.label} must be no more than ${this.errors['maxlength'].requiredLength} charaters`);  
  36.                         break;  
  37.                 }  
  38.             }  
  39.         }  
  40.         return message;  
  41.     }  
  42. }  
  43. exportclass ProductFormGroup extends FormGroup {  
  44.     constructor() {  
  45.         super({  
  46.             name: new ProductFormControl("Name""name"" ", Validators.required),  
  47.             price: new ProductFormControl("Price""price""", Validators.compose([Validators.required,  
  48.                 Validators.pattern("^[0-9\.]+$"),  
  49.                 LimitValidators.Limit(100)  
  50.             ])),  
  51.             category: new ProductFormControl("Category""category""", Validators.compose([Validators.required,  
  52.                 Validators.pattern("^[A-Za-z ]+$"),  
  53.                 Validators.minLength(3),  
  54.                 Validators.maxLength(10)  
  55.             ]))  
  56.         });  
  57.     }  
  58.     get productControls(): ProductFormControl[] {  
  59.         return Object.keys(this.controls).map(k => this.controls[k] as ProductFormControl);  
  60.     }  
  61.     getFormValidationMessage(form: any) {  
  62.         let message: string[] = [];  
  63.         this.productControls.forEach(k => {  
  64.             k.getValidationMessages().forEach(m => message.push(m))  
  65.         });  
  66.         return message;  
  67.     }  
  68. }  
ASP.NET