Tampa Tampa - 3 months ago 38
TypeScript Question

angular2- formbuilder, validators and testing end date is greater then start date

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?

Answer

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