0

I have a start and enddate input tags my html

I use angular the FormBuilder and custom Validators to ensure that that start date and end dates are valid.

In my component here is my snippet:

this.form = fb.group({
            startdate: ['',Validators.compose([Validators.required,ModelValidators.validStartDate])],
            enddate: ['',Validators.compose([Validators.required,ModelValidators.validEndDate])],

        });

Here are my validators:

static validStartDate(control: Control){
        var valid: any;
        valid=null;
        var diff:any;
        diff = new Date(control.value).valueOf() - new Date('1999-01-01').valueOf();
        if (diff>=0){
            valid=true;
        }
        return valid ? null : { validStartDate: true };

    }

    static validEndDate(control: Control){
        var valid: any;
        valid=null;
        var diff:any;
        diff = new Date().valueOf() - new Date(control.value).valueOf();
        if (diff>3600*24){
            valid=true;
        }
        return valid ? null : { validEndDate: true };
    }

Now..how can I validate that the enddate is greater than the start date and that the enddate - startdate is greater then 1 year?

E.g. Is is possible to pass other data to the ModelValidators.validEndDate function?

Tampa
  • 75,446
  • 119
  • 278
  • 425
  • No, but the validator doesn't have to be a static static method. If it wasn't, it could access `this.form`, and the the startdate control – JB Nizet Aug 16 '16 at 16:07

1 Answers1

2

do it like this

this.form = fb.group({
   startdate: ['',Validators.compose([Validators.required,ModelValidators.validStartDate])],
   enddate: ['',Validators.compose([Validators.required,ModelValidators.validEndDate])],
        },{validator: this.validateDates}));

and then in you validator class create the function

validateDates(group: ControlGroup) {
  var valid = false;

  for (name in group.controls) {
    var val = group.controls[name].value

    (...)
  }

  if (valid) {
    return null;
  }

  return {
    areEqual: true
  };
}

See this question for more detail

Community
  • 1
  • 1
rashfmnb
  • 9,959
  • 4
  • 33
  • 44