4

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 Answer 1

12

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>
Sign up to request clarification or add additional context in comments.

2 Comments

thanks and yes I tried it but just want to make sure that it is recommended way or not
yeah I think this is the best way, I couldn't found better way then this so far, also we are using it in all our projects and it works perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.