ng-Mask for String manipulation

3.3k views Asked by At

I am trying to convert/only allowing the Mask defined value in the input. lets say - uppercase. Mask code 'A' regEx : [A-Z]

<input type="text" class="form-control" mask="AAAA">

expecting only [A-Z] uppercase character with range is 4 (ABCD). But the above-mentioned code is neither converting to uppercase nor restricting to type lowercase. Any suggestions will be appreciated. Thanks

3

There are 3 answers

1
Jelle Bruisten On

Do you mean using the pattern attribute? This will restrict it to A-Z, the browser will say the pattern is not correct after submitting.

<input type="text" class="form-control" pattern="[A-Z]{4}">
2
Abhay On

If you want to restrict the user input and show the characters in upper case then may be you can create a directive to achieve that behavior.

For example -

@Directive({
  selector: '[char-mask]'
})
export class CharDirective {
  @Input() upperCase = true;

  @HostBinding('class.upper')
  get upper() {
    return this.upperCase;
  }

  @HostListener('keydown', ['$event'])
  onKeydown(e) {
    if (!this.validateKeyCode(e.keyCode, e.target.value)) {
      e.preventDefault();
    }
  }

  private validateKeyCode(keyCode: number, value: string): boolean {
    var inp = String.fromCharCode(keyCode);
    if ((/[a-zA-Z]/.test(inp)) && (value.length <= 3)) {
      return true;
    }
    const whiteListedCodes = [8, 9, 13, 16, 37, 39];
    if (whiteListedCodes.indexOf(keyCode) > -1) {
      return true;
    }
  }

and use than on the input where the behavior is desired.

<input class="form-control" char-mask />

For implementation you can refer - https://stackblitz.com/edit/angular-char-only-mask?file=src/app/char-mask.ts

I hope it would be helpful.

0
sunny rai On

Here is a solution I found, if you are using ng-Mask which is the third party library.

mask code 'A' contents = > letters (uppercase or lowercase) and digits. but if you look for the regex it doesn't contain any digits.thats why Mask with code 'A' will take input as a number also.

and there is no specific predefined mask for upper and lower case. so we have to go for the custom mask, this like.

markup :
 <input type="text" class="form-control" mask="AAAA" [patterns]="customPatterns">

component: 
 customPatterns: any = {'A': { pattern: new RegExp('\[A-Z0-9\]')}};

this is just a way to do it. regex pattern can be different as per requirement.

please have a look: https://stackblitz.com/edit/uppercase-ng-mask any suggestions will be appreciated.