Search code examples
typescriptangular5angular6angular-validation

Conditional validation in Angular


I want to validate the age from and age to value here.

Rules :

Age from should be less than age To. Age To must be grater than age from

Angular 6.0.7 version

This is the form group defined, there are other form values also, skipped irrelevant entries here.

 myForm = new FormGroup({     
          'ageFrom': new FormControl( ),
          'ageTo': new FormControl(),

        });

This is the html search button should be disabled If the validation fails and should display an error message

 <input type="number"  class="form-control" formControlName="ageFrom" >        
  <input type="number"  class="form-control"  formControlName="ageTo" >
 <button type="submit" class="btn btn-primary ripple" click)="search()">Search</button>        

Had tried custom validator, but messages are not displayed and let me know whether for this use case custom validator is required ?

Tried Angular 6, below option is available

<input min="0" max="5">, but again they can type any number.


Solution

  • Template

    <p style="color: red" *ngIf="myform.invalid">{{myform.errors | json}}</p>
    <form [formGroup]="myform">
        <label>
            from:
            <input type="number" formControlName="from">
        </label>
        <label>
            to:
            <input type="number" formControlName="to">
        </label>
        <button type="submit" [disabled]="myform.invalid">go</button>
    </form>
    

    Controller

    import { Component } from '@angular/core';
    import { FormBuilder, AbstractControl, ValidationErrors } from "@angular/forms";
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
        myform = this.builder.group({
            from: '',
            to: ''
        }, {
            validator: this.isValid
        });
    
        constructor(private builder: FormBuilder) {
        }
    
        isValid(c: AbstractControl): ValidationErrors {
            let diff = c.value.to - c.value.from;
    
            return (diff < 18)
                ? { 'young': 'must be 18 years or older' }
                : null;
        }
    }