0

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

2
  • '/\W{40}/g' is a string literal containing a regex literal, it is wrong. You need /\W{40}/g, without quotes, if you need to set a regex. Commented Jun 23, 2020 at 17:59
  • @WiktorStribiżew I've tried without quotes, I get an error " Failed prop type: Invalid prop mask of type regexp supplied to MaskedInput, expected string." Commented Jun 23, 2020 at 18:06

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.