简体   繁体   English

如何显示自定义验证错误消息

[英]How to display custom validation error message

For my form it has just one input and that's a text area, where the user enters in JSON Code and if the Text is not Valid JSON it should display an error message but for some reason it wont work.对于我的表单,它只有一个输入,这是一个文本区域,用户在其中输入 JSON 代码,如果文本无效 JSON 它应该显示一条错误消息,但由于某种原因它不会工作。

Here's my custom validator:这是我的自定义验证器:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function jsonValidator(control: AbstractControl): ValidationErrors | null {
  try {
    JSON.parse(control.value);
  } catch (e) {
    console.log("Not Valid JSON");
    return { jsonInvalid: true };
  }

  return null;
};

Here is the.ts File这是.ts文件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { jsonValidator } from 'src/app/Validators/jsonValid';

@Component({
  selector: 'app-email-body-editor',
  templateUrl: './email-body-editor.component.html',
  styleUrls: ['./email-body-editor.component.scss']
})
export class EmailBodyEditorComponent implements OnInit {

  errorMsg : string = "Not VALID JSON";

  form = this.fb.group({
    jsonField: [null, [Validators.required , jsonValidator]]

  });

  constructor(private fb: FormBuilder) {
  }

  submit(): void {
    console.log(this.form);
  }

  ngOnInit(): void {

  }   
}

And Finally the HTML File最后是 HTML 文件

<form [formGroup]="form" (submit)="submit()">

    <mat-form-field appearance="fill">

        <mat-label>Textarea</mat-label>
        <textarea matInput
            formControlName="jsonField" 
            cols="1000" 
            placeholder="my custom json here" 
            cdkTextareaAutosize 
            cdkAutosizeMinRows="10"
            cdkAutosizeMaxRows="50">
        </textarea>
    </mat-form-field>
    <br>

    <div *ngIf="form.controls.jsonField.hasError('jsonValidator')">
        {{errorMsg}} 
    </div>

</form>

Your validation error name is jsonInvalid , not jsonValidator .您的验证错误名称是jsonInvalid ,而不是jsonValidator

The name is defined by the return statement in your validator function.该名称由验证器 function 中的 return 语句定义。

return { jsonInvalid: true };

You should use this in your HTML:您应该在 HTML 中使用它:

<div *ngIf="form.controls.jsonField.hasError('jsonInvalid')">
  {{errorMsg}} 
</div>

DEMO: https://stackblitz.com/edit/angular-h89jju演示: https://stackblitz.com/edit/angular-h89jju

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

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