Angular 2 form validations start date <= end date

前端 未结 6 2014
孤街浪徒
孤街浪徒 2020-12-09 05:01

I\'m trying to add validations such that the end date can\'t be before the start date. Unfortunately I have no idea how to do that, and I didn\'t find any helpful advice in

6条回答
  •  难免孤独
    2020-12-09 05:16

    You can also do it with Reactive Forms. The FormBuilder API lets you add custom validators.

    Valid keys for the extra parameter map are validator and asyncValidator

    Example:

    import { Component }  from '@angular/core';
    import { FormGroup, FormBuilder, Validators } from '@angular/forms';
    
    @Component({
      selector: 'reactive-form',
      templateUrl: './reactive-form.html'
    })
    export class ReactiveFormComponent {
    
      form: FormGroup
    
      constructor(private fb: FormBuilder){
        this.createForm();
      }
    
      createForm() {
        this.form = this.fb.group({
          dateTo: ['', Validators.required ],
          dateFrom: ['', Validators.required ]
        }, {validator: this.dateLessThan('dateFrom', 'dateTo')});
      }
    
      dateLessThan(from: string, to: string) {
       return (group: FormGroup): {[key: string]: any} => {
        let f = group.controls[from];
        let t = group.controls[to];
        if (f.value > t.value) {
          return {
            dates: "Date from should be less than Date to"
          };
        }
        return {};
       }
     }
    
    }
    

    Note that I'm comparing the values of the inputs date and from with >, but by default this would be comparing strings. In the live example I'm using angular-date-value-accessor and importing the directive useValueAsDate.

    
    

    With this directive group.controls[from].value and group.controls[to].value returns Date and then I can compare them with <.

    Live example in plunkr

    Credits to Dave's answer

提交回复
热议问题