I'm new to Angular. The closest question I found was:
- Validate html text input as it's typed : But they are using
jquery
The actual project is way too sophisticated but I tried creating a minimal problem statement out of it. I want to validate a date as it is typed-in in real time. I'm using moment
for validation. I created a custom validate()
method which is called on (keydown)="triggerValidate()"
. Inside value()
there are several checks:
- Format should be
MM-DD-YYYY
only. - No date should be less than 1st Jan, 2015.
- No date should be above 31st Dec, 2020.
I've created a stckblitz also. But let me explain my logic.
There's a global varibale isDateValid: boolean
which is set accordingly inside validate()
method. If it is false
then addInvalidStyle()
will be called which will make the border red dynamically. And if it is true
, then removeInvalidStyle()
will be called which will remove then apply dynamic css and set the input field back to normal. Here's my code:
timeselector.component.html
<input [class.warning-border]="isApplied" [(ngModel)]="range" (keydown)="triggerValidate()"/>
timeselector.component.ts
import { ... } from '@angular/core';
import moment from 'moment';
@Component({
...
})
export class TimeselectorComponent {
isDateValid: boolean=true;
startingCalendarYear = 2015;
endingCalendarYear = 2020;
isApplied: boolean = false;
range;
triggerValidate() {
this.validate(this.range);
}
validate(range: string) {
this.isDateValid=true;
const myDate = moment(range, 'MM-DD-YYYY', true);
const lastDayOfCalendarYear = moment([this.endingCalendarYear]).endOf('year');
const firstDayOfCalendarYear = moment([this.startingCalendarYear]).startOf('year');
if (!myDate.isValid()) {
this.isDateValid=false;
this.addInvalidStyles();
}
if (myDate.isAfter(lastDayOfCalendarYear)) {
this.isDateValid=false;
this.addInvalidStyles();
}
if (myDate.isBefore(firstDayOfCalendarYear)) {
this.isDateValid=false;
this.addInvalidStyles();
}
if (this.isDateValid) {
this.removeInvalidStyles();
}
}
addInvalidStyles() {
this.isApplied = true;
}
removeInvalidStyles() {
this.isApplied = false;
}
}
timeselector.component.css
.warning-border {
border: 2.8px solid red;
padding-top: 0.8px !important;
padding-bottom: 3px !important;
}
Or you can directly see this stackblitz. My problem is that I have to press some key to validate my dates as I'm using keydown
. I have to press enter to trigger even when the entered date is correct otherwise it will continue showing red alert. Please help me. Is this achievable or not without using form
of any type.