[英]Angular Error : Displaying error messages for custom Validators
我正在嘗試將自定義驗證器添加到我創建的 angular 表單中。 驗證器本身工作正常,但我現在正嘗試在 state 的表單上添加一條錯誤消息,無論該字段是否不正確或有錯誤。
我遇到了以下網站 ( https://blog.angular-university.io/angular-custom-validators ),我最初從那里獲得了驗證代碼,並且我嘗試按照他們用來添加錯誤消息的示例進行操作。
我已經包含了我的 html 文件:`
<div class="container-fluid text-center">
<form [formGroup]="fg">
<div class="row">
<div class="col-3">
<div class="contactListArea">
<h2>Contacts</h2>
<ul id="list">
<li *ngFor="let contact of contacts;">
<button class="btn btn-primary" type="button" (click)="getContact(contact.id)">
<span class="name">{{contact.firstName}} {{contact.lastName}} </span>
</button>
</li>
</ul>
</div>
</div>
<div class="col-3">
<div class="row">
<div class="main-contact-list">
<div class="form-group mb-3 mr-5 mt-5">
<label class="mb-1">First Name</label>
<input class="form-control" type="text" class="form-control" [(ngModel)]="contact.firstName"
name="Name" formControlName="firstName" placeholder="Enter First Name">
<!-- <small *ngIf="firstName.errors?.nameStrength">
Your password must have Upper Case starting letter an 3 characters.
</small> -->
</div>
`
我還附上了我用來創建驗證器的 ts 文件:`
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function nameValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) {
return null;
}
const nameValid = /[A-Z]{1,}[A-Za-z]{2,}/.test(value)
const noWhite = /^\S*$/.test(value);
const nameValidNoWhite = nameValid && noWhite
return !nameValidNoWhite ? { nameStrength: true } : null;
}
}
`
我還為我的組件包含了 ts 文件,我實際上在其中將驗證器添加到我的表單中:
`
initForm(): void {
let id = Date.now() * Math.random();
this.fg = this.fb.group({
id: [id],
firstName: ['', [Validators.required, nameValidator()]],
lastName: ['', [Validators.required, nameValidator()]],
emailAddress: ['', [Validators.required, Validators.email]],
address1: ['', [Validators.required]],
address2: ['', [Validators.required]],
city: ['', [Validators.required]],
postCode: ['', [Validators.required, postCodeValidator()]],
});
}
`
當我將錯誤代碼添加到表單時,它會破壞表單。 下面的屏幕截圖顯示了發生的情況:屏幕的外觀
what happens when i implement the *ngIf statement:根據教程網站使用 ngIf 命令時會發生什么
我按照 web 鏈接中提到的示例進行操作,當我添加語句並包含 *ngIf 語句時,說明如果輸入不符合要求,則強度為假,應顯示錯誤消息。 它基本上破壞了應用程序。
我不確定代碼的第一部分(這是來自網站的示例):*ngIf="password.errors?.passwordStrength"
應該是我選擇的輸入的表單控件名稱?
所以我設法弄清楚如何添加錯誤消息。
所以我有一個驗證器附加到“姓氏”字段,它基本上說如果它不符合標准那么它是一個錯誤。
在我的 html 模板中,我添加了以下代碼:
<span class="help-block"
*ngIf="fg.get('firstName')?.errors && fg.get('firstName')?.touched">
Your Name must have Upper Case starting letter and 3 characters. </span>
這段代碼的作用 它基本上引用了我們為表單組分配的變量 (fg),然后我們使用 get 語句將我們分配的表單控件名稱 (firstName) 拉到我們要使用的字段,我們 state如果有任何錯誤,如果該字段已被觸摸,則發出以下錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.