简体   繁体   中英

Regular expression allow numbers and digits validation pattern

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"]
          }
        ],

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM