Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2439

regex expression to allow user type any symbols

I'm using react-maskedinput and for mask it accept regular expression . I'm getting mask from backend . Sometimes mask is empty and I need to set default mask. If it's empty I want to allow user type any 40 symbols.

export function getMaskForInput(mask) {
  const newMask = mask.toString().replace(/`9/g, 'q').replace(/9/g, '1').replace(/q/g, '`9');
  const emptyMask = '/\W{40}/g';  // probably not correct expression
  if (mask) {
    return newMask.replace(/`/g, '\\').replace('$', '');
  }
  console.log('empty mask');

  return emptyMask;
}

const mask = getMaskForInput(maskEdit)

<MaskedInput
  mask={mask}
  type="tel"
  id="account"
  autoComplete="off"
  maxLength={40}
  placeholder="№ лицевого счета"
  placeholderChar=" "
  onChange={(e) => this.handleOnAccountChange(e.target.value.trim())}
  value={this.state.account}
  formatCharacters={{
     W: {
     validate(char) { return /[\wа-яА-Я \-0-9.@]/.test(char); },
     },
     w: {
     validate(char) { return /[\wа-яА-Я \-0-9.@]/.test(char); },
     }
}}
/>

But when I return 'emptyMask' it shows my actual regex for mask . Where I'm making mistake?

enter image description here

Upvotes: 0

Views: 1003

Answers (1)

Miguel Ventura
Miguel Ventura

Reputation: 10458

I think you're misunderstanding how the MaskedInput component works.

MaskedInput's mask format string is not a regular expression. It's a user-friendly string. You can use strings like "11-11" which would be equivalent to the regular expression /^\d\d-\d\d$/.

This format string has some characters you can use out of the box1, a, A, * and # represent classes of characters (eg: 1 represents any digit), and symbols (such as - or / represent themselves).

You can define your own symbol classes, which is what you're doing with w and W — you're defining those classes as anything that matches the regular expression [\wа-яА-Я \-0-9.@].

However to mask 40× your custom character class, you can't use W{40} because {40} is valid for a regex but not for the mask string. Remember that mask is not a regular expression. So if you want a mask that matches 40× the W class, you need to use "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", or "W".repeat(40).

Upvotes: 3

Related Questions