Search code examples
validationangular2-forms

Angular 2 form validations start date <= end date


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 the internet so far. My form looks like this:

editAndUpdateForm(tageler: Tageler) {
    this.tageler = tageler;
    this.tagelerForm = this.fb.group({
      title: [this.tageler.title, Validators.required],
      text: this.tageler.text,
      group: [[this.tageler.group], Validators.required],
      date_start: new Date(this.tageler.start).toISOString().slice(0, 10),
      date_end: new Date(this.tageler.end).toISOString().slice(0, 10),
      ...
    });
    this.tagelerForm.valueChanges
       .subscribe(data => this.onValueChanged(data));
    }

My validations so far:

onValueChanged(data?: any) {
    if (!this.tagelerForm) {
      return;
    }
    const form = this.tagelerForm;

    for (const field in this.formErrors) {

    // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
}

validationMessages = {
    'title': {
      'required': 'Geben Sie bitte einen Namen ein.',
    },
    'group': {
      'required': 'Wählen Sie bitte eine Gruppe aus.'
    },
    'bringAlong': {
      'required': 'Bitte Feld ausfüllen.'
    },
    'uniform': {
      'required': 'Bitte Feld ausfüllen.'
    },
};

formErrors = {
    'title': 'Geben Sie bitte einen Namen ein.',
    'group': 'Wählen Sie bitte eine Gruppe aus.',
    'bringAlong': 'Bitte Feld ausfüllen',
    'uniform': 'Bitte Feld ausfüllen',
};

The the form-controls 'date_start' & 'date_end' contain a date-string of the form 'dd.MM.yyyy', and I want 'date_end' to be bigger or equal 'date_start'.

I'd like to directly display the error message (my html code looks like this:)

<label for="formControlName_date_end" class="col-3 col-form-label">Ende:</label>
      <div class="col-5">
        <input id="formControlName_date_end" class="form-control" formControlName="date_end" type="date" value="{{tageler.end | date: 'yyyy-MM-dd'}}">
      </div>
      <div *ngIf="formErrors.date_end" class="alert alert-danger">
        {{ formErrors.date_end }}
      </div>

Could someone help me?

Thanks!


Solution

  • we cant do it in validation because we need two control values that is startdate and enddate for comparison. So it is better to compare two dates in your component

    error:any={isError:false,errorMessage:''};
    
    compareTwoDates(){
       if(new Date(this.form.controls['date_end'].value)<new Date(this.form.controls['date_start'].value)){
          this.error={isError:true,errorMessage:'End Date can't before start date'};
       }
    }
    

    In your html

    <label for="formControlName_date_end" class="col-3 col-form-label">Ende:</label>
    <div class="col-5">
          <input id="formControlName_date_end" class="form-control" formControlName="date_end" type="date" value="{{tageler.end | date: 'yyyy-MM-dd'}}" (blur)="compareTwoDates()">
    </div>
    <div *ngIf="error.isError" class="alert alert-danger">
       {{ error.errorMessage }}
    </div>