Validation rules
isIP
Summary
Sails provides the isIP
validation rule to ensure that a string only contains a valid IPv4 or IPv6 address. This is useful when storing IP addresses in your models and preventing invalid values.
For example, consider the ip
attribute:
ip: {
type: 'string',
isIP: true
}
This ensures that only valid IPv4 or IPv6 addresses are accepted.
Key takeaways:
isIP
ensures a string is a valid IP address.Supports both IPv4 and IPv6 formats.
Invalid values will trigger a validation error.
If we try to create a user with an invalid value:
await User.create({ ip: "not.an.ip" });
Sails will return an error:
"not.an.ip"
is not a valid IP address.
But passing a valid IP works fine:
await User.create({ ip: "192.168.1.1" }); // Success!
await User.create({ ip: "2001:db8::ff00:42:8329" }); // Success!
This validation rule ensures data consistency by preventing non-IP values from being stored.
Transcript
Another validation rule you might need occasionally is the isIP
validation rule, which ensures a string is a valid IPv4 or IPv6 address.
Let’s add an ip
field to our User model:
ip: {
type: 'string',
isIP: true
}
This ensures only valid IP addresses can be stored.
Testing the Validation Rule
I’ll open Guppy and try creating a user:
await User.create({ ip: "not.an.ip" });
This fails because "not.an.ip"
is not a valid IP:
"not.an.ip"
is not a valid IP address.
Now, let’s test with valid IPv4 and IPv6 addresses:
await User.create({ ip: "192.168.1.1" }); // ✅ Works!
await User.create({ ip: "2001:db8::ff00:42:8329" }); // ✅ Works!
If we modify the IP (e.g., adding extra digits), Sails will correctly reject it:
await User.create({ ip: "192.168.1.999" }); // ❌ Invalid!
This ensures only proper IPv4 and IPv6 addresses are stored.
Full Course
USD