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;
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With