I am trying to validate an ipv4 address with the prefix for the subnet mask (CIDR notation).
Is there a way to do this with ajv or with the ajv-format package?
my first attempts (in ts) look like this:
type typeIpv4 = {
ipv4: string
}
const schemaIpv4: JSONSchemaType<typeIpv4> = {
type: "object",
properties: {
ipv4: {
type: "string",
format: "ipv4"
}
},
required: ["ipv4"]
}
example, incoming json:
{
ipv4: "192.168.100.14/24",
}
a not very nice solution is to cut out the IP address, validate it with ajv and test the mask by hand (programmatically) itself:
const ip: typeIpv4 = { ipv4: ipv4.split("/")[0] }
const validateIp = ajv.compile(schemaIpv4);
For example joi offers the cidr notation as validation option:
const schema = joi.string().ip({
version: [
'ipv4',
'ipv6'
],
cidr: 'optional'
});
I have read the documentary of ajv but i might have misunderstood something.
UPDATE:
work-around: I split the string and parse the mask to an Int/number
const splitIpv4 = ipv4.split("/")
const ip: typeIpv4 = {
ipv4: splitIpv4[0],
cidr: parseInt(splitIpv4[1])
}
I have added the additional property cidr to the schema. Now the validation goes over the range of valid subnet masks (0-32 corresponds to 0.0.0.0 - 255.255.255.255)
...
cidr: {
type: "number",
minimum: 0,
maximum: 32
}
...
The problem here is that it is not looked whether the specified IP address is a network or broadcast address in the subnet.
question from:
https://stackoverflow.com/questions/66050374/how-to-validate-the-subnet-mask-with-ajv 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…