How to Add Custom Validation Error Message for Custom Validator in Angular

Viewed 9043

I'm using reactive angular forms and created new custom form validator but its not showing custom messages I wanted to add custom message for custom validator.

I'm trying to ignore static message I want that message to be added in that validator itself so it can show for wherever places I use that validator.

custom validator codes :

import { FormControl } from '@angular/forms';

export function validateJson(input: FormControl): object | null {
    try {
        if (input.value) {
            JSON.parse(input.value);
        }

        return null;
    } catch (error) {
        return { invalidFormat: true };
    }
}
1 Answers

just change invalidFormat property's value to object with property message instead of true

import { FormControl } from '@angular/forms';

export function validateJson(input: FormControl): object | null {
    try {
        if (input.value) {
            JSON.parse(input.value);
        }

        return null;
    } catch (error) {
        return { invalidFormat: {message: "your message here"} };
    }
}

and in html if error exists display message like so

<div *ngIf="formControl.errors.invalidFormat && formControl.dirty">
        {{ formControl.errors.invalidFormat.message}}
</div>
Related