角反应形式 - 自定义验证器
问题描述:
我有一个要求,某些输入字段需要被屏蔽。例如,期望的金额应该显示为44444美元。我可以通过使用文本掩码来实现输入掩码(https://github.com/text-mask/text-mask)。我遇到的问题是屏蔽会破坏我的被动式表单验证器。角反应形式 - 自定义验证器
组件:
import {WithinLoanRangeDirective} from './within-loan-range.directive'
this.applicationForm = this.fb.group({
desiredAmount: ['', [Validators.required, WithinLoanRangeDirective] ]
})
模板:
<input
[textMask]="{mask: numberMask}"
mdInput
formControlName="desiredLoanAmount
type="tel"
> <!--type tel to pop numpad-->
<div> {{ applicationForm.controls['desiredLoanAmount'].hasError('withinLoanAmountRange')}}</div>
的验证们正在检查,而不是(44444)最小值和最大值对蒙面输入($ 44444)。在将模型设置为模型之前是否有格式化该值的方法?
答
您需要创建一个自定义验证器(指令)并去除所有非数字字符并将最小最大值设置为参数(或者在指令中硬编码它们),然后返回有效性。
https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
import { Directive } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';
@Directive({
selector: '[ngModel][withinLoanAmountRange], [formControl][withinLoanAmountRange]',
providers: [
{
provide: NG_VALIDATORS,
useClass: WithinLoanRangeDirective,
multi: true,
}
]
})
export class WithinLoanRangeDirective implements Validator {
constructor() {
}
validate(c: FormControl) {
let loanValue = c.value.replace(/\D/g,'');
return (loanValue >= 1000 && loanValue <= 20000) ? null : {
withinLoanAmountRange: { message: 'Loan Needs to be between 1 and $5k' }
};
}
}
<input
[textMask]="{mask: numberMask}"
withinLoanAmountRange
mdInput
formControlName="desiredLoanAmount
>
如何获取withinLoanAmountRange.message回到模板?认为我错过了一些东西来获得这种连线。我在“let loanValue”之后放置了一个console.log(loanValue),并且在输入时没有任何内容被打印到控制台。 – Anthony
模板中的applicationForm .controls ['desiredLoanAmount'] .hasError('withinLoanAmountRange'))' – wesside
或者,您可以将指令导入组件,并将其添加到验证程序数组中,而不是在模板中。 – wesside