4

I have a simple form with only one date control in it. When I type an invalid date like 30-Feb-2018, the control is in invalid state and my CSS style kicks in and control is shown with red border.

My problem is that, when the user clicks save, this.appFormGroup.invalid returns false and a save operation is performed. How do I stop the save operation (I want to inform the user that the date is invalid?)

The following code demonstrates the issue that I am facing:

app.component.ts file

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  appFormGroup: FormGroup;

  constructor(public formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.appFormGroup = this.formBuilder.group({
      sampleDate: ['']
    });
  }

  onButtonClick() {
    if (this.appFormGroup.invalid) {
      alert("Invalid");
    }
    else {
      alert("Valid");
    }
  }
}

app.component.html file

<form [formGroup]="appFormGroup">
  <div >
    <div>
      <label for="sampleDate">Sample Date</label>
      <input type="date" [id]="sampleDate" formControlName="sampleDate" min="" class="form-control-dynamic">
    </div>
    <button (click)="onButtonClick()">Save</button>
  </div>
</form>

app.components.css file

input[type="date"]:invalid {
    border-width : 2px;
    border-color: red;
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Anand Murali
  • 4,091
  • 1
  • 33
  • 46

2 Answers2

1

In your form control you have not used any validation. First remove min attr from HTML and create a custom date validator and use that validator, when you are creating control. To avoid error on blank don't use required and return true from custom validator if value is there and it's invalid.

sampleDate: ['', [DateValidator]] //don't use required


function DateValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (control.value !== undefined && YOUR_CUSTOM_VALIDATION_LOGIC) {
            return { 'dateInvalid': true }
        };
        return null;
    }
}
Robin gupta
  • 176
  • 2
  • 11
  • 1
    Hi Robin, thanks a lot for you answer. I'm afraid this will not solve my problem, because the `control.value` property returns `""` for both invalid date case and for the case when user clicks the X button in the date picker. To put it in other words, the `control.value` property always has a valid date or an empty value. – Anand Murali Jun 05 '18 at 13:21
  • @AnandMurali did you ever solve this? It's 5 years later and I have the same problem as you. – James Gardner Feb 14 '23 at 22:35
0

The thing is that your Angular form is not doing any validation on the date, hence why it's not invalid.

You will need to add a validator onto your form e.g.

sampleDate: ['', [Validators.required, customDateValidator]

You will probably need to create your own Date Validator see here

Then if your custom validator returns that the date is not valid, the form property invalid will be set to true.

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83
  • 1
    Hi Jamie, Thanks a lot for your time. I had thought of this approach, but the problem for me is that if the date is invalid, the custom validator is triggered with empty value. I cannot raise error when value is empty because, empty is a valid value when the user clicks the X button in the date control – Anand Murali Jun 05 '18 at 12:39