Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular and text-mask: Regex to validate an input without special characters

I have angular 5 with "angular2-text-mask": "^8.0.4" https://github.com/text-mask/text-mask/tree/master/angular2

What I'm trying to do is preventing users entering special characters, except for -, _, ', which should be allowed for a name type="text" input.

This works for phone numbers:

<input [textMask]="{mask: mask}" [(ngModel)]="myModel" type="text"/>

public myModel = ''

public mask = ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]

But when I try public mask = [/^[a-zA-Z]+$/]; which is supposed to accept multiple letters, however I can only write one. What's wrong? I like to be able to enter unlimited letters, digits and -, _, '

I tested my mask at https://regex101.com/

Any help is appreciated.

like image 259
LieutenantDan Avatar asked Mar 28 '18 15:03

LieutenantDan


2 Answers

This text-mask is not a regular expression. Documentation says that

mask is an array or a function that defines how the user input is going to be masked. Each element in the array has to be either a string or a regular expression. Each string is a fixed character in the mask and each regular expression is a placeholder that accepts user input.

Your mask is an array containing one character. This means that it will accept only one character that matches /^[a-zA-Z]+$/.

If you want multiple characters, you need an array of regular expressions for each of them, like this:

public mask = [/[a-zA-Z]/, /[a-zA-Z]/, /[a-zA-Z]/];

This mask will accept three letters.

like image 197
Kirill Simonov Avatar answered Nov 08 '22 20:11

Kirill Simonov


I know it happened a few months ago but I found a way to do it.

You can create a function which receives as a parameter the raw value and returns a regexp array.

So, you just basically receive the raw value, count the lenght and you push the mask to the array.

I did it like this:

<input [textMask]="{mask: nameMask, guide: false}" [(ngModel)]="myModel" type="text"/>

nameMask(rawValue: string): RegExp[] {
    const mask = /[A-Za-z]/;
    const strLength = String(rawValue).length;
    const nameMask: RegExp[] = [];

    for (let i = 0; i <= strLength; i++) {
      nameMask.push(mask);
    }

    return nameMask;

}
like image 40
megustalafantabienfria Avatar answered Nov 08 '22 18:11

megustalafantabienfria