celsomtrindade
celsomtrindade

Reputation: 4671

Angular 2 validate input based on mask

I'm using this plugin within my Angular 2 project to mask some inputs.

The problem I have with this is to validate if the input has the proper mask applied.

Whenever I try to check for the value it's alwayas valid. For example, I have a mask to fill a phone number, just like in the example:

@Component({
  template: `
    <input [textMask]="{mask: mask}" type="tel" formControlName="phone" />
  `
})

export class AppComponent {
  public myModel = ''
  public mask = ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
}

But even when I fill, let's say, 2 numbers (11_) ___-____ it's considering the field as valid.

I tried to se a custom Validator to check for the input length, but it's also passing, since it's being prefilled with _.

this.registerForm = this._fb.group({
    'phone': [null, Validators.compose([
        Validators.required,
        Validators.minLength(14),
        Validators.maxLength(14)
    ])],
});

I don't know how to create a validation for this type of scenario, envolving more complex validations.

Upvotes: 3

Views: 2725

Answers (1)

Paulo Pedroso
Paulo Pedroso

Reputation: 3685

Just registering the correct answer from @developer033. It worked like a charm for me.

The following should work as expected: Validators.pattern(/^([1-9]\d{2})\s\d{3}-\d{4}$/);

Although I used a pattern that fit my needs.

Upvotes: 1

Related Questions