0

I am trying to check if a form input is valid based on a regex pattern using javascript.

The form input should look like this: xxxx-xxx-xxxx allowing for both numbers and letters

Right now it only works with digits as I have it setup which is now being changed to allow letters as well. is there a way to change the regex I have to allow numbers and letters and still format as is?

4 letters or numbers A DASH 3 letters or numbers A DASH 4 letters or numbers

validation rule
  medNumber: [
          {
            required: true,
            pattern: /^\d{4}?[- ]?\d{3}[- ]?\d{4}$/,
            message: "Please enter your #.",
            trigger: ["submit", "change", "blur"]
          }
        ],

2 Answers 2

4

[A-Za-z0-9] will match only alphanumeric characters.

/^[A-Za-z0-9]{4}?[-]?[A-Za-z0-9]{3}[-]?[A-Za-z0-9]{4}$/

I've also removed the spaces from within your instances of [- ] because that will allow matches such as

xxxx xxx xxxx

In your spec you mention a dash is required, not a space.

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

Comments

2

The rule \d allows only for digits. So you need to change every occurrence of this to \w, which allows any alphanumeric character (letters and digits). So you'd get the following:

/^\w{4}?[- ]?\w{3}[- ]?\w{4}$/

For future reference, I'd suggest looking at regexone.com. It has helped me a ton with learning all the regex rules. You can also use regex101.com for easy testing of regex patterns.

Edit:
I was probably a bit too quick on this one. As @David mentioned in the comment, \w also includes underscores. If you don't want that, you should look at his answer instead :)

2 Comments

Just a heads up that \w also matches underscores _
@David Ah! I completely forgot about that. Thanks for the heads-up. I edited my answer to reference yours if he'd prefer without underscores :)

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.