Heathcliff
Heathcliff

Reputation: 119

Display cross field custom validation error message

In my reactive form i have built a custom validation for 3 input fields. The main function of the validation is to return a error when either 1/2 out of 3 input fields have a value (I want all 3 fields to be required as soon as the user enters a value in 1 field).

This is my validator:

public addressValidator(control: AbstractControl): { [key: string]: boolean } | null {

    const zip= control.get('zip');
    const houseNumber= control.get('houseNumber');
    const street= control.get('street');

    if ((zip?.value !== "" || houseNumber?.value !== "" || street?.value !== "") &&
        (zip?.value === "" || houseNumber?.value === "" || street?.value === "")) {
        console.log("form not valid");
        return { 'invalid': true };
    }   return null;
}

ngOnInit:

ngOnInit(): void {
    this.contactForm = this.fb.group(
        {
            addition: "",
            residence: ["", [
                Validators.required
            ]],
            phone: "",
            mobile: "",
            address: this.fb.group({
                street: ['', [
                ]],
                houseNumber: ['', [
                ]],
                zip: ['', [
                ]],
            }, { validator: this.adresValidator } )
        });

HTML:

<ng-container formGroupName="address">
    <div class="col-12">
        <mat-form-field class="w-100">
            <mat-label>Street</mat-label>
            <input matInput formControlName="street">
            <mat-error *ngIf="street.errors?.invalid">Field is mandatory</mat-error>
        </mat-form-field>
    </div>

I am using Angular Material to display an error message but even though my console.logs tell me the validation is applied, I cant seem to display the messages in my template. I have tried the code in the HTML example as well as some other lines, but they are either deprecated or not working.

My question is, how do I display the error in my template? (note: address is a nested formGroup )

Upvotes: 2

Views: 3526

Answers (1)

IAfanasov
IAfanasov

Reputation: 4993

The validator is added to the this.contactForm itself. So the errors would be on the contactForm group.

<mat-error *ngIf="contactForm.errors?.invalid">Field is mandatory</mat-error>

Upvotes: 2

Related Questions