gpt4 book ai didi

Angular 自定义验证器错误(预期验证器返回 Promise 或 Observable)

转载 作者:行者123 更新时间:2023-12-02 20:14:19 25 4
gpt4 key购买 nike

我为电话字段编写了一个自定义验证器并获取
错误

Expected validator to return Promise or Observable.

为简单起见,我只需要检查电话号码是否少于 10 个字符

html

<div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
!ersaForm.get('phone').valid
}">

<label for="phoneId" class="control-label">Phone</label><br />
<p-inputMask mask="(999) 999-9999" formControlName="phone" inputStyleClass="form-control" [style]="{'width': '100%','height':'34px'}" id="phoneId" placeholder="Phone (required)"></p-inputMask>
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
ersaForm.get('phone').errors">
<span *ngIf="ersaForm.get('phone').errors.phonePBXCheck">
invalivd Phone Number.
</span>

</span>

</div>

TS

function phoneCheck(phone: string): ValidatorFn{
return (c: AbstractControl): { [key: string]: boolean } | null => {

var phoneVal = c.value;
phoneVal = phoneVal.replace('(', '');
phoneVal = phoneVal.replace(')', '');
phoneVal = phoneVal.replace('-', '');
phoneVal = phoneVal.replace('_', '');
phoneVal = phoneVal.replace(' ', '');
console.log('custom validation ' + phoneVal);
if (c.value != undefined && isNaN(c.value) || phoneVal.lenght<10) {
return { 'phonePBXCheck': true };
};
return null;
};
}

this.ersaForm = this._fb.group({
phone: ['', Validators.required, phoneCheck('')],
});

我错过了什么?

最佳答案

编辑:您只需将验证器包装在数组中即可。

 this.ersaForm = this._fb.group({
phone: ['', [Validators.required, phoneCheck('')]],
});

此外,作为建议,您可以从验证器中删除这些行:

phoneVal = phoneVal.replace('(', '');
phoneVal = phoneVal.replace(')', '');
phoneVal = phoneVal.replace('-', '');
phoneVal = phoneVal.replace('_', '');
phoneVal = phoneVal.replace(' ', '');

而是使用 p-inputMaskunmask 属性来保持模型值干净:

 <p-inputMask mask="(999) 999-9999" formControlName="phone" 
inputStyleClass="form-control"
[unmask]="true"
[style]="{'width': '100%','height':'34px'}" id="phoneId"
placeholder="Phone (required)">
</p-inputMask>

更新:经过一番尝试后,我注意到 p-inputMask 不支持其他验证器,它只提供 required 属性对于您来说,即使您的自定义验证器被调用,控件本身也将保持有效。

关于Angular 自定义验证器错误(预期验证器返回 Promise 或 Observable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743336/

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