I am new to angular development and I am stuck at a point where I need to perform the validation on the dynamically added rows.
I use template-driven forms. I have two fields ValidFrom and ValidTo and an array of blackout dates {fromdate and todate}
. The model is below
export interface Rooms {
validFrom?: Date | string;
validTo?: Date | string;
blackOutDateVM?: BlackOutDateVM[];
}
export class BlackOutDateVM {
validFrom?: Date;
validTo?: Date;
}
Currently, I use this function when the user is going to submit the form to validate the dates.
ValidateRateForDatesAndTax(): boolean {
this.isFormValid = true;
if (this.rateDetail.isContainsBlackOutDates === true) {
this.rateDetail.blackOutDateVM.forEach(item => {
if (item.validFrom < item.validTo) {
this.rateValidator.isBlackOutDatesValid = false;
} else {
this.rateValidator.isBlackOutDatesValid = true;
}
if (item.validFrom === null || item.validFrom === undefined) {
this.rateValidator.isBlackOutDatesValid = false;
this.isFormValid = false;
} else {
this.rateValidator.isBlackOutDatesValid = true;
}
if (item.validTo === null || item.validTo === undefined) {
this.rateValidator.isBlackOutDatesValid = false;
this.isFormValid = false;
} else {
this.rateValidator.isBlackOutDatesValid = true;
}
if (
item.validFrom === null ||
item.validFrom === undefined ||
(item.validTo === null || item.validTo === undefined)
) {
if (
item.validFrom > this.rateDetail.validTo ||
item.validTo < this.rateDetail.validFrom
) {
this.rateValidator.isBlackOutDatesValid = false;
this.isFormValid = false;
} else {
this.rateValidator.isBlackOutDatesValid = true;
}
}
});
}
return this.isFormValid;
}
I want to make sure that blackout dates should be within the valid from and valid to dates. Can anyone let me know how to perform this validation in angular?
I would suggest you to use form builder service of angular,
So let me suggest you how you should go about doing this,
Write a custom validation function such that it acts like you would write a function onchange event
yourValidationFunctionFrom(){}
yourValidationFunctionTo(){}
create a form instance (if this is required)
`this.yourForm = this._fb.group({ BlackOutDate: this._fb.array([this.fb.control('From',[yourValidationFunctionFrom]),
this.fb.control('To',[yourValidationFunctionTo])]) });`
Using form builder you can do a lot of operation a lot easily, you will be surprised that angular has so much packed in it for our help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.