angular - 显示跨字段自定义验证错误信息
问题描述
在我的反应式表单中,我为 3 个输入字段构建了自定义验证。验证的主要功能是在 3 个输入字段中有 1/2 有值时返回错误(我希望用户在 1 个字段中输入值后立即要求所有 3 个字段)。
这是我的验证器:
public addressValidator(control: AbstractControl): { [key: string]: boolean } | null {
const zip= control.get('zip');
const houseNumber= control.get('houseNumber');
const street= control.get('street');
if ((zip?.value !== "" || houseNumber?.value !== "" || street?.value !== "") &&
(zip?.value === "" || houseNumber?.value === "" || street?.value === "")) {
console.log("form not valid");
return { 'invalid': true };
} return null;
}
ngOnInit:
ngOnInit(): void {
this.contactForm = this.fb.group(
{
addition: "",
residence: ["", [
Validators.required
]],
phone: "",
mobile: "",
address: this.fb.group({
street: ['', [
]],
houseNumber: ['', [
]],
zip: ['', [
]],
}, { validator: this.adresValidator } )
});
HTML:
<ng-container formGroupName="address">
<div class="col-12">
<mat-form-field class="w-100">
<mat-label>Street</mat-label>
<input matInput formControlName="street">
<mat-error *ngIf="street.errors?.invalid">Field is mandatory</mat-error>
</mat-form-field>
</div>
我正在使用 Angular Material 来显示错误消息,但即使我的 console.logs 告诉我验证已应用,我似乎也无法在我的模板中显示消息。我已经尝试过 HTML 示例中的代码以及其他一些行,但它们要么已被弃用,要么无法正常工作。
我的问题是,如何在模板中显示错误?(注意:地址是一个嵌套的 formGroup )
解决方案
验证器被添加到this.contactForm
自身。所以错误将在contactForm
组上。
<mat-error *ngIf="contactForm.errors?.invalid">Field is mandatory</mat-error>
推荐阅读
- reactjs - npx create-react-app 导致漏洞
- c# - OR 运算符用法
- python-3.x - 如何使用 django rest framework api 将文件上传到 s3 存储桶
- c++ - 不存在合适的构造函数来将“int()”转换为“std::function”
" - mule4 - 收到此错误 org.mule.runtime.api.store.ObjectAlreadyExistsException: Object already exists for the key
- php - Laravel 查询生成器在 where 子句之后加入
- c - C - 此代码中递归的返回部分有什么问题?
- arrays - 如何检查数组的第一个元素和一些 jsx
- node.js - 使用 Node.js 在终端中运行 java 脚本时出错
- python - 如何修复 Kivymd MDDataTable python3 的“内联错误”