2

In this demo i have created a sample form for custom validator, here i have From date and TO date and from time and To time, working fine: For from date and to date validation working fine and showing error messages.

problem: when choosing same date , eg) july 21 2018 as from date and same in To date and In from Time be 4:00 Am and To Time be 3:00AM, the condition gets satisfied, but which is not showing an error message.Somethis went wrong in implementation,can anyone help me to solve appreciated

In html i have given validation message but which gets not displayed.

To Time:
<input type="time" formControlName="ToTime">
    <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>

In component:

 DaterForm : FormGroup;

constructor(private fb:FormBuilder){
}
   ngOnInit(){

 this.DaterForm = this.fb.group(
{
  FromDate:['',[AppCustomDirective.fromDateValidator]], // validation working fine
  FromTime:[''],
  ToDate:['',[AppCustomDirective.ToDateValidator]],// validation working fine
  ToTime:['']
},{validator:[AppCustomDirective.timeValidator] // validation not working
}

Custom validation:

import { AbstractControl, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';

export class AppCustomDirective extends Validators{

   static fromDateValidator(fdValue: FormControl) {
    const date = fdValue.value;
    console.log('x');
    if (date ===null || date==='') return { requiredFromDate: true };

  }

   static ToDateValidator(todValue: FormControl) {
    const date = todValue.value;

    if (date ===null || date==='') return { requiredToDate: true };

  }


  static timeValidator(formGroupValues: FormGroup): any {
    debugger;
    console.log(formGroupValues);
    const FromDate = formGroupValues.get('FromDate').value;
    const ToDate = formGroupValues.get('ToDate').value;
    const FromTime = formGroupValues.get('FromTime').value;
    const ToTime = formGroupValues.get('ToTime').value;

    if (FromDate.toString() === ToDate.toString()) {
      let fromTime = [];
      let toTime = [];
      fromTime = FromTime.split(':');
      toTime = ToTime.split(':');
      if (parseInt(fromTime[0]) > parseInt(toTime[0])){
      alert("condition satisfied not return any error message");
         return { InValidToTime: true };
        }
      else if (
        parseInt(fromTime[0]) === parseInt(toTime[0]) &&
        parseInt(fromTime[1]) > parseInt(toTime[1])
      ){  alert("condition satisfied not return any error message")
        return { InValidToTime: true };
      }
    }
  }
}

live demo

2
  • ' InValidToTime': remove this leading space. There might be other problems, but I stopped reading at that point. Commented Jul 20, 2018 at 20:44
  • @JBNizet that is typo while pasting , i think which is an implementation issue while return error,if you want to look the demo see herehttps://stackblitz.com/edit/angular-customvalidator?file=app%2Fdatepicker-overview-example.html Commented Jul 20, 2018 at 21:13

1 Answer 1

5

Its because you are setting errors on your form while you expect for error to be on particular input.

Changing to <mat-error *ngIf="DaterForm.hasError('InValidToTime')"> Fixes the issue.

FYI this is not how mat-error is designed to be used with <input matInput/>

https://stackblitz.com/edit/angular-customvalidator-1fu5vx?file=app/datepicker-overview-example.html

Sign up to request clarification or add additional context in comments.

3 Comments

@why error which is not working when move the mat-error inside mat-form-field <mat-form-field> <mat-error *ngIf="DaterForm.get('ToDate').hasError('requiredToDate')">Please provide a valid Todate</mat-error> when move after mat-form field which is working
Its because you are using it wrong way. It is designed to display errors of particular input. Input must be in error state (have not null errors) or mat-error will be hidden. Its not ngIf in controll of WHEN error is displayed (inside matInput) but controll state. This is forked example wit forcibly "fixed" issue, but it is not how mat-error should be use. stackblitz.com/edit/angular-customvalidator-xksspd?file=app/… . You can read Angular Material documentaion on examples to see how to properly handle and show input errors (with animations etc).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.