我为电话领域写了一个自定义验证器,
错误
期望的验证器,以返回Promise或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('')],
});
我错过了什么?
答案 0 :(得分:3)
编辑:您只需要将验证器包装在数组中即可。
this.ersaForm = this._fb.group({
phone: ['', [Validators.required, phoneCheck('')]],
});
此外,作为建议,您可以从验证器中删除这些行:
phoneVal = phoneVal.replace('(', '');
phoneVal = phoneVal.replace(')', '');
phoneVal = phoneVal.replace('-', '');
phoneVal = phoneVal.replace('_', '');
phoneVal = phoneVal.replace(' ', '');
,而是使用unmask
的{{1}}属性来保持模型值整洁:
p-inputMask
更新:玩了一段时间之后,我注意到 <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
属性调用后,控件本身将保持有效。