Validation rules
isHexColor
Summary
Sails provides the isHexColor
validation rule to ensure that a string only contains a valid hexadecimal color. This is useful when storing color values in your models.
For example, consider the themeColor
attribute:
themeColor: {
type: 'string',
isHexColor: true
}
This ensures that only valid hex color values (e.g., #000000
, #FFF
, #1a2b3c
) are accepted.
Key takeaways:
isHexColor
ensures a string is a valid hex color.Supports 3-digit (
#000
) and 6-digit (#000000
) formats.Allows optional
#
prefix (e.g.,#FF5733
).Invalid values will trigger a validation error.
If we try to create a user with an invalid value:
await User.create({ themeColor: "not-a-color" });
Sails will return an error:
"not-a-color"
is not a valid hexadecimal color.
But passing a valid hex color works fine:
await User.create({ themeColor: "#FF5733" }); // ✅ Works!
await User.create({ themeColor: "ABC" }); // ✅ Works! (Equivalent to #AABBCC)
This validation rule ensures data consistency by preventing invalid colors from being stored.
Transcript
Let’s look at a validation rule that ensures a string is a valid hexadecimal color.
We’ll add a themeColor
field to our User model:
themeColor: {
type: 'string',
isHexColor: true
}
This ensures only valid hex colors can be stored.
Testing the Validation Rule
I’ll open Guppy and try creating a user:
await User.create({ themeColor: "not-a-color" });
This fails because "not-a-color"
is not a valid hex code:
"not-a-color"
is not a valid hexadecimal color.
Now, let’s test with valid hex colors:
await User.create({ themeColor: "#000000" }); // ✅ Black
await User.create({ themeColor: "FFF" }); // ✅ White (#FFFFFF)
await User.create({ themeColor: "#1a2b3c" }); // ✅ Works!
If we modify the color with incorrect values (e.g., missing digits), Sails will correctly reject it:
await User.create({ themeColor: "ZZZ" }); // ❌ Invalid!
This ensures only proper hex colors are stored in the database.
Full Course
USD