angular2 – Angular 2, Data Validation and Input Mask Issue

Question:

I have implemented form validation according to the tutorial https://auth0.com/blog/angular-2-series-part-5-forms-and-custom-validation/

            <input class="form-control"
                   type="text"
                   name="phone"
                   autocomplete="off"
                   placeholder="(XXX)-XXX-XXXX"
                   mask=""
                   [disabled]="disabled"
                   [(ngModel)]="candidate.phone"
                   ngControl="phone"/>

static phone(control: Control): ValidationResult {

    let URL_REGEXP = /^\(\d{3}\)-\d{3}-\d{4}$/i;

    if (control.value && (control.value.length <= 5 || !URL_REGEXP.test(control.value))) {

        return {"phone": true};
    }

    return null;
}

plus for this form element I have implemented the input mask directive: http://pastebin.com/wRzHSsVy

The problem arises in the following: when you enter a phone number, first the validation is triggered and then the mask directive, so it turns out that the data that the validator checks and the data that the mask directive formats are different, for example, on the validator the phone number (888) -888-88882 and the mask results type number (888) -888-8888 but the validator has already worked and issued an error before the mask was triggered.

How can a validator be called after an input mask directive is triggered?

Answer:

HTML:

<input type="text" class="form-control" name="phone" placeholder="Phone" [(ngModel)]="myclass.phone" [pattern]="PHONE_PATTERN" [textMask]="{mask: PHONE_MASK}"/>

ts:

static PHONE_PATTERN = /\(\d{3}\)\-\d{3}\-\d{4}/;
static PHONE_MASK = ['(', /[1-9]/, /\d/, /\d/, ')', '-', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
Scroll to Top