Reputation: 143
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.
1111-111111-1111
- (valid according to my business logic)12341234561234
- (valid according to my business logic)1111-111111111
- (I want this to be not valid)1111111111-1111
- (I want this to be not valid)Upvotes: 2
Views: 2531
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 stringAnother 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 stringUpvotes: 2
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
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