Difference between revisions of "Validating Date from and Date to"

From Basef
Jump to: navigation, search
(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...')
 
 
Line 37: Line 37:
 
</source>
 
</source>
  
[[Category: AngularJS2]]
+
[[Category: Angular]]

Latest revision as of 10:39, 27 January 2020

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 {};
    }
  }
}