繁体   English   中英

如何获取角度表单验证错误消息?

[英]How to get the angular form validation error message?

我的源代码可以通过以下 URL 访问:

https://stackblitz.com/edit/angular-aidmpq?file=src%2Fapp%2Fapp.component.html

我想问以下编码:

<mat-error *ngIf="logRecipients.errors.required">
    Appreciation Log Recipients is <strong>required</strong>
  </mat-error>
  <mat-error *ngIf="logRecipients.errors.logRecipientValidator">
    Invalid email address
  </mat-error>

为什么“logRecipients.errors.required”报如下错误?

Cannot read property 'required' of null

为什么“logRecipients.errors.logRecipientValidator”提示如下错误?

Cannot read property 'logRecipientValidator' of null

我想获得内置的“必需”验证器结果来决定是否显示“鉴赏日志收件人是必需的”消息。

我想获得我的自定义验证器结果来决定是否显示“无效的电子邮件地址”消息。 如果验证失败,我的验证器将返回一个对象 {email:true},我该如何读取此属性?

您应该首先检查logRecipients.errors是否为空、空或未定义,然后检查特定错误。

所以改变你的代码如下:

第 14 行有 2 个变化:

  1. 必需的验证在错误对象内,因此将<mat-error *ngIf="logRecipients.required">更改为<mat-error *ngIf="logRecipients.errors.required">
  2. 检查错误对象本身,因此将<mat-error *ngIf="logRecipients.errors.required">更改为<mat-error *ngIf=" logRecipients.errors && logRecipients.errors.required">

第 17 行有同样的问题(检查错误对象本身),将*ngIf="logRecipients.errors.logRecipientValidator"更改为*ngIf="logRecipients.errors && logRecipients.errors.logRecipientValidator"

完整的工作代码:

  <form #callTreeEditForm="ngForm" (ngSubmit)="onSubmit(callTreeEditForm)">
    <mat-form-field style="width:250px">
      <mat-label>Appreciation Log Recipients</mat-label>
      <textarea matInput
                cdkTextareaAutosize
                #autosize="cdkTextareaAutosize"
                cdkAutosizeMinRows="1"
                cdkAutosizeMaxRows="5"
                required
                name="logRecipients"
                #logRecipients="ngModel"
                logRecipientValidator
                [(ngModel)]="this.callTree.logRecipients"></textarea>
      <mat-error *ngIf="logRecipients.errors &&logRecipients.errors.required">
        Appreciation Log Recipients is <strong>required</strong>
      </mat-error>
      <mat-error *ngIf="logRecipients.errors && logRecipients.errors.logRecipientValidator">
        Invalid email address
      </mat-error>
    </mat-form-field>

  </form> 

希望这有帮助。 :)

在某些时候logRecipients是未定义的,为了解决这个问题,只需检查它是否存在,然后对该对象进行后续的属性检查。

  <mat-error *ngIf="logRecipients && logRecipients.required">
    Appreciation Log Recipients is <strong>required</strong>
  </mat-error>
  <mat-error *ngIf="logRecipients && logRecipients.errors && logRecipients.errors.logRecipientValidator">
    Invalid email address
  </mat-error>

只需使用 angular 已经为我们提供... template expression operator ( ? ) 所以现在,您可以通过将属性设置为可选来检查属性是否已定义。

<mat-error *ngIf="logRecipients?.errors?.logRecipientValidator">
    Invalid email address
</mat-error>

我想获得我的自定义验证器结果来决定是否显示“无效的电子邮件地址”消息。 如果验证失败,我的验证器将返回一个对象 {email:true},我该如何读取此属性?

我认为你把它复杂化了。 记住你在打字稿中设置的自定义验证的返回类型

{[键:字符串]:任何}

这是javascript。 您可以将任何内容附加为键值对,并使用键的字符串获取该值引用。 您可以更改验证的逻辑以根据您想要的内容更改消息或返回全新的内容。 只需确保您的模板涵盖所有场景。 以下是从验证函数返回消息的示例:

validate(control: AbstractControl): {[key: string]: any}|null {
if ((control.dirty) && (control.valid)) {
  const logRecipients = control.value.trim().split('\n');
  const tempBox = this.renderer2.createElement('input');
  let result = null;
  tempBox.type = 'text';

  for (const logRecipient of logRecipients) {
    tempBox.value = logRecipient;
    result = (Validators.email(tempBox));
    // console.log(logRecipient + ',' + result);
    if (result != null) {
      break;
    }
  }
  // console.log('Return :' + result);
  console.log(result);
  return {email: 'The email address is invalid. Custom Message'};
} else {
  // console.log('Return null');
  return null;
}

应用组件.html

 <form #callTreeEditForm="ngForm" (ngSubmit)="onSubmit(callTreeEditForm)">
<mat-form-field style="width:250px">
  <mat-label>Appreciation Log Recipients</mat-label>
  <textarea matInput
            cdkTextareaAutosize
            #autosize="cdkTextareaAutosize"
            cdkAutosizeMinRows="1"
            cdkAutosizeMaxRows="5"
            required
            name="logRecipients"
            #logRecipients="ngModel"
            logRecipientValidator
            [(ngModel)]="this.callTree.logRecipients"></textarea>
  <mat-error *ngIf="logRecipients.hasError('required')">
    Appreciation Log Recipients is <strong>required</strong>
  </mat-error>
  <mat-error *ngIf="logRecipients.hasError('email')">
    {{logRecipients.errors['email']}}
  </mat-error>
</mat-form-field>

抱歉,我忘了将指令添加到 app.module.ts 中。

我找到了如下解决方案:

  <mat-error *ngIf="logRecipients.hasError('required')">
    Appreciation Log Recipients is <strong>required</strong>
  </mat-error>
  <mat-error *ngIf="logRecipients.hasError('email')">
    Invalid email address
  </mat-error>

可以通过以下 URL 访问工作代码:

https://stackblitz.com/edit/angular-aidmpq?file=src%2Fapp%2Fapp.component.html

暂无
暂无

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

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