Skip to content

Commit

Permalink
Angular Forms In Depth
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Dec 15, 2020
1 parent a010946 commit 0f69262
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@

</mat-date-range-input>

<mat-error *ngIf="form.errors?.promoPeriod && form.dirty">
The start date must be before the end date.</mat-error>

<mat-datepicker-toggle matSuffix [for]="promoPicker"></mat-datepicker-toggle>

<mat-date-range-picker #promoPicker></mat-date-range-picker>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {createPromoRangeValidator} from '../../validators/date-range.validator';


@Component({
Expand All @@ -19,6 +20,9 @@ export class CreateCourseStep2Component implements OnInit {
]],
promoStartAt: [null],
promoEndAt: [null]
}, {
validators: [createPromoRangeValidator()],
updateOn: 'blur'
});

constructor(private fb: FormBuilder) {
Expand Down
19 changes: 19 additions & 0 deletions src/app/validators/date-range.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {FormGroup, ValidatorFn, Validators} from '@angular/forms';


export function createPromoRangeValidator(): ValidatorFn {
return (form: FormGroup): Validators | null => {

const start:Date = form.get("promoStartAt").value;

const end:Date = form.get("promoEndAt").value;

if (start && end) {
const isRangeValid = (end.getTime() - start.getTime() > 0);

return isRangeValid ? null : {promoPeriod:true};
}

return null;
}
}

0 comments on commit 0f69262

Please sign in to comment.