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