首页 文章

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

提问于
浏览
0

我要求屏蔽某些输入字段 . 例如,所需金额应显示为$ 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

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

    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              
     >
    

相关问题