Search code examples
angular

How to validate date using reactive form in angular if user select date greater than today date


Cam anybody suggest How to validate date using reactive form in angular if user select date greater than today date. I want to show error message .If user select greater than today date

Thanks


Solution

  • You can reactively set a validator for min and max dates based off of the current date although no default Angular validator currently exists. You'll need to create a custom validator..

    import { FormControl, ValidationErrors } from '@angular/forms';
    
    export class DateValidator {
    
       static LessThanToday(control: FormControl): ValidationErrors | null {
            let today : Date = new Date();
    
           if (new Date(control.value) > today)
               return { "LessThanToday": true };
    
           return null;
       }
    }
    

    Import the DateValidator class into your component where the reactive form is created, and apply the validator described above. (It may need tweaking, I've not tested it..)