0

I want to limit the number of letters at the beginning and end of the input value (e.g. QQ23F and SG21G) through JavaScript but I found that only one {} can be written in a pattern. Thanks for any help. Here is my incorrect code:

var isValid = true;
  var id=document.getElementById("pid").value;
  if (!id.match(/[A-Za-z]{2}+[0-9]+[A-Za-z]{1}/)) {
      document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
      isValid = false;
  }
3
  • {2}+ is invalid; did you mean perhaps {2,} (for 2 or more)? Commented Aug 24, 2022 at 13:20
  • Hi Nick, I just want to have 2 letters only at the starting. Commented Aug 24, 2022 at 13:24
  • 2
    Then just use {2} and get rid of the + Commented Aug 24, 2022 at 13:25

1 Answer 1

1

You need to add the begging ^ and end $ signs

  let isValid = true;
  let id=document.getElementById("pid").value;
  if (!id.match(/^([A-Za-z]{2}[0-9]+[A-Za-z]{1})$/)) {
      document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
      isValid = false;
  }

And for everyone's sake use let not var

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

3 Comments

Hi, thanks for your help. I tried this again but the console still says Uncaught SyntaxError: Invalid regular expression
@RyanYan, I updated my code. Please check.
@RyanYan, Glad to hear that. Please mark that as the answer to the question.

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.