Anand Murali
Anand Murali

Reputation: 4109

Angular date - invalid input not being marked as invalid on form submit

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;
}

Upvotes: 4

Views: 3707

Answers (2)

Robin gupta
Robin gupta

Reputation: 196

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;
    }
}

Upvotes: 1

Jamie Rees
Jamie Rees

Reputation: 8183

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.

Upvotes: 0

Related Questions