Harleen Kaur Arora
Harleen Kaur Arora

Reputation: 2087

How to set min length validation in phone number masking in angular2-text-mask?

I am working on angular 4 application and I am using angular2-text-mask for phone number masking. As you provide that user can not enter more number then available in masking but I also want that the user should enter a proper number according to masking if user enter less number then masking required it will show an error.

Upvotes: 1

Views: 2153

Answers (2)

Engineer_Andrew
Engineer_Andrew

Reputation: 604

I'm going to put this answer here for anyone who comes across this question in the future. You can create a custom validator that will ignore the masking characters and then just apply that minLength validator instead of the built-in one:

import { Injectable } from '@angular/core';
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class MaskedLengthValidator {
  static minLength(minLength: number, replace?: Array<string>): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (this.isEmptyInputValue(control.value)) {
        return null;  // don't validate empty values to allow optional controls
      }

      let value = control.value;

      if (!!replace && !!replace.length) {
        replace.forEach(c => {
          var regEx = new RegExp(c, 'g');
          value = value.replace(regEx, "");
        });
      } else {
        value = control.value.replace(/_/g, "");
      }

      const length: number = value ? value.length : 0;
      return length < minLength ?
          {'minlength': {'requiredLength': minLength, 'actualLength': length}} :
          null;
    };
  }

  static maxLength(maxLength: number, replace?: Array<string>): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {    
      let value = control.value;

      if (!!replace && !!replace.length) {
        replace.forEach(c => {
          var regEx = new RegExp(c, 'g');
          value = value.replace(regEx, "");
        });
      } else {
        value = !!value ? control.value.replace(/_/g, "") : value;
      }

      const length: number = value ? value.length : 0;
      return length > maxLength?
          {'maxLength': {'requiredLength': maxLength, 'actualLength': length}} :
          null;
    };
  }

  static isEmptyInputValue(value: any): boolean {
    // we don't check for string here so it also works with arrays
    return value == null || value.length === 0;
  }
}

Once you've got the validator class created, you can use it just like any other validator:

[Validators.required, MaskedLengthValidator.minLength(7), MaskedLengthValidator.maxLength(7)]

The validator I've provided here will automatically ignore underscores, or you can specify an array of characters to ignore:

[Validators.required, MaskedLengthValidator.minLength(7, ['_', '-']), MaskedLengthValidator.maxLength(7)]

Upvotes: 1

Vega
Vega

Reputation: 28738

You can also check if it's less numbers and set an error label, or disable the submit button based on the input length. Example:

<input class="form-control" id="orderId" required minlength="5" 
type="number" name="orderId" [ngModel]="orderIdModel" 
(ngModelChange)="orderIdModel = $event + ''" #orderId="ngModel" /> 

<span style="color:red" *ngIf="orderId.errors?.required">
       required
</span>
<span style="color:red" *ngIf="orderId?.value.length <= 5">
      5 minimum
</span>

<button [disabled]="orderId?.value.length <=5" type="submit">Submit</button>

Upvotes: 0

Related Questions