Validating Date from and Date to

From Basef
Revision as of 15:11, 23 April 2018 by Admin (Talk | contribs) (Criou página com 'To create a custom validation with date from and date to: <source lang="javascript"> import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Valid...')

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

To create a custom validation with date from and date to:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
 
export class ReportsComponent implements OnInit {
 
  reportsForm: FormGroup;
 
  constructor(private fb: FormBuilder) {
 
  }
 
  ngOnInit() {
    this.reportsForm = this.fb.group({
      startDate: [''],
      endDate: ['']
    }, {validator: this.dateLessThan('startDate', 'endDate')});
  }
 
  dateLessThan(from: string, to: string) {
    return (group: FormGroup): { [key: string]: any } => {
      const inputFrom = group.controls[from];
      const inputTo = group.controls[to];
      const bothFilled = inputFrom.value && inputTo.value;
 
      if (bothFilled && inputFrom.value > inputTo.value) {
        return {
          dates: "A data início deve ser menor ou igual à data fim."
        };
      }
      return {};
    }
  }
}