gpt4 book ai didi

对于 ng-select 控件的自定义验证,Angular 2 表单状态始终无效

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

我在用户信息表单中使用了验证,如下所示。

this.userInfoForm = this.fb.group({
retrieveId: [''],
customerName: [[],[UtilityService.checkMinLength(3, 50)]],
});

我创建了以下服务来检查验证

 @Injectable()
export class UtilityService {
static checkMinLength(min: number, max: number): ValidatorFn {
return (c: AbstractControl) => {
if (c.value && c.value != undefined) {
return {
'checkMinLength': c.value.some((a) => {
if (a.itemName.length < min || a.itemName.length > max) { return true; }
return null;
})
};
}
}
}

在 HTML 中使用 checkMinLength 检查 customername 字段的有效性。这些验证工作正常,但当我检查表单状态时,它显示“无效”。对于 ng-select 控件,提交按钮始终处于禁用状态

<form class="form-horizontal" novalidate (ngSubmit)="saveInfo()" [formGroup]="userInfoForm" autocomplete="off">
<fieldset>
<div class="form-group padding-top-bottom" [ngClass]="{'has-error': (userInfoForm.get('customerName').touched || userInfoForm.get('customerName').dirty) &&!userInfoForm.get('customerName').valid }">
<label class="col-md-4" for="customerNameId" tooltip={{attributeNames.customerNameTitle}} data-placement="right">Customer Name</label>
<div class="col-md-7">
<ng-select [items]="customerName" multiple="true" [addTag]="true" bindLabel="itemName" (change)="onItemSelect($event,'customer','customerName')" formControlName="customerName" [(ngModel)]="customerName"></ng-select>
<span class="help-block" *ngIf="userInfoForm.get('customerName').touched ||userInfoForm.get('customerName').dirty) &&userInfoForm.get('customerName').errors">
<span *ngIf="userInfoForm.get('customerName').errors.checkMinLength">End Customer Name must be longer than 3 characters.</span>
</span>
</div>
</div>
<button class="btn btn-primary" id="submitForm" type="submit" [disabled]="!userInfoForm.valid || !userInfoForm.dirty">Save</button>
</fieldset>
</form>

最佳答案

如果控件有效,您的验证器必须返回“null”(不是具有 null 属性的对象)

export class UtilityService {
static checkMinLength(min: number, max: number): ValidatorFn {
return (c: AbstractControl) => {
if (c.value && c.value != undefined) {
return {
'checkMinLength': c.value.some((a) => {
if (a.itemName.length < min || a.itemName.length > max) { return true; }
})
};
}
return null; // LOOK HERE
}
}

关于对于 ng-select 控件的自定义验证,Angular 2 表单状态始终无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444154/

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