Angular reactive form - custom validator -
i have requirement input fields need masked. example, desired amount should displayed $44,444. can achieve input masking using text-mask (https://github.com/text-mask/text-mask). problem encountering masking breaks reactive form validators.
component:
import {withinloanrangedirective} './within-loan-range.directive' this.applicationform = this.fb.group({ desiredamount: ['', [validators.required, withinloanrangedirective] ] })
template:
<input [textmask]="{mask: numbermask}" mdinput formcontrolname="desiredloanamount type="tel" > <!--type tel pop numpad--> <div> {{ applicationform.controls['desiredloanamount'].haserror('withinloanamountrange')}}</div>
the validators checking min , max against masked input ($44,444) instead of (44444). there way format value before setting in model?
you need create custom validator (directive) , strip out non-numeric characters , set min max arguments (or hard code them in directive..), return validity.
https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
import { directive } '@angular/core'; import { ng_validators, validator, formcontrol } '@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 between 1 , $5k' } }; } } <input [textmask]="{mask: numbermask}" withinloanamountrange mdinput formcontrolname="desiredloanamount >
Comments
Post a Comment