1

I want to define quantity of symbols in my regex

_keyPress(ptrn: string, event: any) {
    const pattern = new RegExp(ptrn);
    const inputChar = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    const value = event.target.value;
    if (!pattern.test(inputChar) && !pattern.test(value)) {
      event.preventDefault();
      return false;
    }
  }

html:

<input (keypress)="_keyPress('[a-z]{,6}', $event)">

But it doesn't work if I use quantity quantifier. Who can say what's going wrong? https://plnkr.co/edit/fIVAvRJcubzD2SxZqlTY?p=preview

3
  • Try setting 0 as the minimum value - [a-z]{0,6}. Better with anchors to require the full string match - ^[a-z]{0,6}$ Commented Jun 12, 2017 at 10:17
  • is it comming in _keyPress function you tried to console log in the function Commented Jun 12, 2017 at 10:27
  • @Wiktor Stribiżew No, it doesn't work Commented Jun 12, 2017 at 12:06

1 Answer 1

1

First of all event.charCode returns number between 97 and 122 for a-z. So, the pattern.test(inputChar) test always fails because you are trying to compare digits to alphabets. So, change inputChar to following:

const inputChar = String.fromCharCode(event.key ? event.which : event.key);

Also, value needs to be updated with the next key entered by user:

const value = (event.target.value) + inputChar;

I am assuming you are trying to restrict the user from enter any keys except a-z and only allowing them enter up to 6 alphabets. Therefore, the final test needs an || flag instead of &&, because the input should be allowed when both of tests pass, not just when one of them pass.

if (!pattern.test(inputChar) || !pattern.test(value)) {
      event.preventDefault();
      return false;
    }

Here's the Plnkr demo forked from yours.

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.