Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 };
    }
}
like image 617
Mohit Bumb Avatar asked Oct 29 '25 09:10

Mohit Bumb


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>
like image 143
Artyom Amiryan Avatar answered Oct 31 '25 00:10

Artyom Amiryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!