简体   繁体   English

如何在 Angular 中为自定义验证器添加自定义验证错误消息

[英]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 };
    }
}

just change invalidFormat property's value to object with property message instead of true只需将invalidFormat属性的值更改为具有属性消息而不是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如果存在错误,则在 html 中显示这样的消息

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM