angularangular5custom-validators

How to make comparison between two dates in angular5?


I'm trying in angular5 to not validate a form if the second date input is greater than the first date input and then show an error message ,so the user can change the date .

This is .html file :

    <div class="modal-body">
    <form [formGroup]="form" (ngSubmit)="addProjecToClients()">
        <div class="form-group row">
          <label class="col-sm-5 col-form-label">Choisir un client : </label>


          <div class="col-sm-6">

            <ng-select  *ngIf="_listClients"
                         [items]="_listClients"
                          bindLabel ="nom"
                          bindValue ="id"
                        [(ngModel)]="selectedPersonId"
                        formControlName="selectedPersonId"
                         >
            </ng-select>

          </div>
        </div>

        <label class="col-sm-5 col-form-label">Information liées au contrat : </label>
        <div class="form-group row">
          <label class="col-sm-5 col-form-label" >Date one :  </label>
          <div class="col-sm-6">
            <input type="date" class="form-control form-control-sm"
                   placeholder=".form-control-sm"  [(ngModel)]="dateOne"
formControlName="dateOne">
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-5 col-form-label" for="input-small">Date two : </label>
          <div class="col-sm-6">
            <input type="date" id="input-small" name="input-small" class="form-control form-control-sm"
                   placeholder=".form-control-sm"  [(ngModel)]="dateTwo" 
    formControlName="dateTwo">

 <span style="color:red" *ngIf="validation()">DateTwo must be gt than dateone</span>

          </div>
        </div>
      </div>

     <button type="submit" class="btn btn-primary"  [disabled]="!form.valid" >Save changes</button>

</form>

This is .ts File :

 export class ProjectsComponent implements OnInit {

    dateOne:new Date() ;
    dateTwo:new Date(); 

     ngOnInit() {

    this.doSearch();
    this.dateOne= null;
    this.dateTwo= null;

 this.form = this.formBuilder.group({
      dateOne: ['', Validators.required],
      dateTwo: ['', Validators.required],
       selectedPersonId: ['', Validators.required]
    });

}

validation(){
    if(this.dateOne && this.dateTwo){
      if(this.dateOne.getTime() < this.dateTwo.getTime()){
        return false;
      }
      else
        return true;
    }

      }

    }

I was advised to use custom validators, but I couldn't find a complete simple example.

Any help :) ?


Solution

  • Try by using this code getTime() to compare in milliseconds.

    if(dateOne.getTime() > dateTwo.getTime())