Angular-自定义验证不会显示错误消息

问题描述 投票:0回答:1

对于我的Form,它只有一个输入,这是一个文本区域,用户在其中输入JSON代码,如果Text不是有效的JSON,它应该显示一条错误消息,但由于某种原因它将无法正常工作。谢谢大家的帮助,谢谢大家!

这是我的自定义验证器:

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;
    };

这是.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 {

  }


}

最后是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>
json angular typescript validation angular-forms
1个回答
1
投票

您的验证错误名称是jsonInvalid,而不是jsonValidator

名称由验证器函数中的return语句定义。

return { jsonInvalid: true };

您应该在HTML中使用它:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.