角度反应形式 - 自定义验证器

时间:2017-07-27 20:59:29

标签: angular

我要求屏蔽某些输入字段。例如,所需金额应显示为$ 44,444。我可以使用text-mask(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>

验证器现在正在检查屏蔽输入($ 44,444)而不是(44444)的最小值和最大值。有没有办法在模型中设置之前格式化值?

1 个答案:

答案 0 :(得分:0)

您需要创建自定义验证器(指令)并去除所有非数字字符并将最小值设置为参数(或在指令中对它们进行硬编码),然后返回有效性。

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              
 >
相关问题