user1814595
user1814595

Reputation: 143

RegEX 14 digits validation with dash separator

I'm using the following regex ^[\d]{4}[-]?[\d]{6}[-]?[\d]{4}$ to validate 14 numbers as a whole or divided as

4 digits - 6 digits - 4 digits

the following four examples are matching my regex but i want to exclude the last two example.

Upvotes: 2

Views: 2531

Answers (3)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can do a negative look ahead for patterns you don't want to match and use this regex,

^(?!\d{4}-\d{10})(?!\d{10}-\d{4})\d{4}-?\d{6}-?\d{4}$

Explanation:

  • ^ --> Start of string
  • (?!\d{4}-\d{10}) --> Negative lookahead to avoid matching this pattern
  • (?!\d{10}-\d{4}) --> Negative lookahead to avoid matching this pattern
  • \d{4}-?\d{6}-?\d{4} --> Matches the pattern as you wanted
  • $ --> End of string

Demo

Another pattern I could think of, is more simple and elegant, you can use is this,

^\d{4}(-?)\d{6}\1\d{4}$

Explanation:

  • ^ --> Start of string
  • \d{4} --> Matches exactly four digits
  • (-?) --> Matches an optional hyphen and captures in group 1
  • \d{6} --> Matches exactly six digits
  • \1 --> This ensures that both hyphens are either present or are absent as mentioned in the regex
  • \d{4} --> Matches exactly four digits
  • $ --> End of string

Demo

Upvotes: 2

Sayantan Mandal
Sayantan Mandal

Reputation: 1336

^([\d]{4}[-]?[\d]{6}[-]?[\d]{4})|([\d]{16})$

Hope this helps! it has two regex one with hiphens another with whole number(16 digits)

Upvotes: 0

epascarello
epascarello

Reputation: 207537

Just use an or with the pattern or 14 numbers.

var re = /^(\d{4}-\d{6}-\d{4}|\d{14})$/

function test(str) {
  console.log(str, re.test(str))
}

['1234-123456-1234', '12341234561234',
'1234-1234561234', '1234123456-1234'].forEach(test)

Upvotes: 2

Related Questions