diff --git a/src/app/crossValidator.service.ts b/src/app/crossValidator.service.ts new file mode 100644 index 0000000..0ba55b7 --- /dev/null +++ b/src/app/crossValidator.service.ts @@ -0,0 +1,22 @@ +import { AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from "@angular/forms"; + +export class CrossValidator { + public onlyAllowNameAndDescriptionSame() { + return (control: AbstractControl): ValidationErrors | null => { + if (!(control instanceof FormGroup)) { + return null; + } + + const name = control.get('name')?.value; + const description = control.get('description')?.value; + + console.log(name, description); + + const error = name !== description ? { mismatch: true } : null; + + console.log(error); + + return error; + }; + } +} diff --git a/src/app/new-hotel/new-hotel.component.html b/src/app/new-hotel/new-hotel.component.html index 1e7e9a1..a72d1ed 100644 --- a/src/app/new-hotel/new-hotel.component.html +++ b/src/app/new-hotel/new-hotel.component.html @@ -1,6 +1,8 @@

Create Hotel

+
{{ errorMessages['form'] }}
+
{{ errorMessages['name'] }}
diff --git a/src/app/new-hotel/new-hotel.component.ts b/src/app/new-hotel/new-hotel.component.ts index a6755b7..b89763b 100644 --- a/src/app/new-hotel/new-hotel.component.ts +++ b/src/app/new-hotel/new-hotel.component.ts @@ -4,6 +4,7 @@ import { AbstractControl, FormArray, FormControl, FormGroup, ReactiveFormsModule import { Router, RouterLink } from '@angular/router'; import { Hotel } from '../HotelItem/hotel'; import { NgFor, NgIf } from '@angular/common'; +import { CrossValidator } from '../crossValidator.service'; @Component({ selector: 'app-new-hotel', @@ -24,6 +25,10 @@ export class NewHotelComponent { pattern: "The value format is incorrect" }; + private fullFormValidationErrorMessages: Record = { + mismatch: "The name and description have to be the same", + } + updateErrorMessages(): void { this.errorMessages = {}; @@ -37,6 +42,14 @@ export class NewHotelComponent { } }); + + if (this.hotelForm.errors) { + Object.keys(this.hotelForm.errors).forEach(errorKey => { + const errorMessage = this.fullFormValidationErrorMessages[errorKey] || `Unknown error: ${errorKey}`; + this.errorMessages['form'] = errorMessage; + }); + } + console.log(this.errorMessages); } @@ -55,7 +68,7 @@ export class NewHotelComponent { imageUrl: new FormControl("", Validators.required), rating: new FormControl(0, Validators.required), tags: new FormArray(tags) - }) + }, { validators: new CrossValidator().onlyAllowNameAndDescriptionSame() }) this.hotelForm.valueChanges.subscribe(() => this.updateErrorMessages()); }