cidr-regex
cidr-regex copied to clipboard
Short prefix notation support?
cidrRegex.v4({ exact: true }).test('65.0/14') (which is a short notation for 65.0.0.0/14) does not validate as an IPv4 CIDR (although it does validate as such in other libraries and tools such as python IPy). Is this expected behaviour?
I've seen these in use but think they are rather confusing. I'd suggest raising this issue first on ip-regex first, maybe they want to support it with an option which this module could then copy.
I just went over and took a look at ip-regex, and I am a little confused. It seems to only support single IP addresses, and short notation such as 65.0/14 only applies to CIDR. I am not sure what they have to do with it, but perhaps I am missing something?
I made a quick and dirty workaround in my own code, if it helps you at all:
// Support short format prefixes
if (text.includes('/') && !cidrRegex.v4({ exact: true }).test(text) && !cidrRegex.v6({ exact: true }).test(text)) {
const slashparts = text.split('/')
const dotparts = slashparts[0].split('.')
let realIP = ''
if (!dotparts) {
realIP = slashparts[0] + '.0.0.0'
} else {
dotparts.forEach(element => { realIP += element + '.' })
if (dotparts.length === 1) {
realIP = realIP + '0.0.0'
}
if (dotparts.length === 2) {
realIP = realIP + '0.0'
}
if (dotparts.length === 3) {
realIP = realIP + '0'
}
}
correctedVal = realIP + '/' + slashparts[1]
}
short notation such as 65.0/14 only applies to CIDR
It's a entirely user-defined convention (that to my knowledge was never standardized) but I can't see why it should not work for IPs too. 65.0 can unambiguously expanded to 65.0.0.0 but a issue arises once there is only a single digit, e.g. 65 can both be IPv4 and IPv6, same goes for 65/12.
I think that ambiguitity makes it kind of unsuitable for these modules and essentially this would just be another form of IP normalization. I'd suggest making a new module that would normalize these IP/CIDR abbreviations, trim leading 0 digits, lowercase hex digits, collapse ipv6 zeroes etc. to a single normalized representation for both v4 and v6. Maybe I'll do somthing like that myself later.
I'm not against this, but first the change has to be accepted in ip-regex first, maybe with an option, because we outsource that part of the regex from there.