gpt4 book ai didi

javascript - 如何在 Angular 4 中显示来自自定义验证器函数的自定义错误消息?

转载 作者:太空狗 更新时间:2023-10-29 17:57:04 24 4
gpt4 key购买 nike

请考虑以下自定义验证器函数,它在后端调用 API 来获取一些数据,根据当前表单输入检查它们,如果当前表单输入是重复值,则返回错误:

//check to see if the new category name entered is already in the system
categoryNameUnique(c: FormControl) {
let categoryNameAlreadyExists: boolean = false;

//get list of current categories from the server.
return this.inventoryCategoryService.getAll().map(items => {
for (let item of items) {
if (item.Name == c.value) {
categoryNameAlreadyExists = true;
break;
}
}

if (categoryNameAlreadyExists) {
//name is not unique
return { categoryNameUnique: false }
}
//not a duplicate, all good
return null;
});
}

您会看到此函数正在返回一个可观察对象(因为我必须返回到后端服务器以获取一些数据以进行验证)。验证器就像一个魅力,没有问题。但是,当此验证器在我相应的 HTML View 中返回无效时,我不知道如何向用户显示适当的消息。如果这个函数没有返回一个可观察对象,我会做类似的事情:

<div *ngIf="form.controls['categoryName'].errors?.categoryNameUnique">
This category name is already taken
</div>

但是,由于这是一个返回的可观察对象,错误对象具有由可观察对象公开的属性,即 operatorsource,而不是我的自定义对象m 返回 ({categoryNameUnique: false}).

如有任何帮助,我们将不胜感激。

更新 1:

大家好,在尝试了一些其他的东西之后,我能够找出我自己的问题。

我是这样设置我的表单验证的:

constructor(private fb: FormBuilder, private router: Router, private inventoryCategoryService: InventoryCategoryService) {
this.form = fb.group({
'categoryName': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50), this.categoryNameUnique.bind(this)])]
});
}

必需的、minLength 和 maxLength 验证器是同步的,但我的自定义验证器 categoryNameUnique 是异步的,因此应该单独组成。我将设置更改为下面的设置,现在一切正常:

constructor(private fb: FormBuilder, private router: Router, private inventoryCategoryService: InventoryCategoryService) {
this.form = fb.group({
'categoryName': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
Validators.composeAsync([this.categoryNameUnique.bind(this)])]
});
}

最佳答案

我认为您的问题可能是您如何将异步验证器应用于控件。根据您对 form.controls.categoryName 的使用情况,我假设您正在使用 formbuilder 来创建表单。在这种情况下,您需要提供异步验证器作为组参数数组中的第三个参数,如下所示:

this.form = this.formBuilder.group({
categoryName: ["", [], [categoryNameUnique]]
});

像这样设置后,您应该能够如预期的那样在错误中看到它。

我首选的显示自定义验证错误的方式是这样的:

<div *ngIf="form.controls.categoryName.hasError('categoryNameUnique')">
The category name is not unique!
</div>

关于javascript - 如何在 Angular 4 中显示来自自定义验证器函数的自定义错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com