Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 230
celsomtrindade Avatar asked Jan 21 '26 03:01

celsomtrindade


1 Answers

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.

like image 190
Paulo Pedroso Avatar answered Jan 23 '26 19:01

Paulo Pedroso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!