Validation rules
isNotIn
Summary
The isNotIn
validation rule in Sails allows you to blacklist specific string values for an attribute. Unlike isIn
, which specifies a whitelist of allowed values, isNotIn
defines a list of values that are not permitted.
For example, when defining a username
attribute, you may want to prevent users from setting names like "admin"
, "superadmin"
, or "user"
because they are too generic. The rule only applies to the string
data type and does not support numbers or other types.
One important caveat is that the validation checks for an exact match. If a user adds extra spaces (e.g., "admin "
), it may bypass the blacklist. To prevent this, you should trim input values before validation. When implemented correctly, this rule is useful for preventing restricted words in usernames, chat messages, or other text fields.
Transcript
In as much as we can whitelist some allowed values for an attribute using the isIn
validation rule, we could also blacklist using the opposite of the isIn
validation, which is the isNotIn
validation rule.
So if we go to Visual Studio Code right now, let's say we're going to allow our user to have an alias, which is pretty much like a username.
Let’s go to the top. In here, we have a username
attribute, which would be like a nickname, right? Of course, it's going to be of type string
.
And we want every word to be allowed except certain restricted ones, like "admin"
, "superadmin"
, or even just "user"
because it's too generic as a username. So we could do this:
username: {
type: 'string',
isNotIn: ['admin', 'superadmin', 'user']
}
This sets a blacklist, meaning these values are not allowed. Unlike isIn
, which specifies allowed values, isNotIn
defines values that are forbidden.
It's also important to note that isNotIn
applies only to the string
data type, not numbers or other types.
Now, if we go to Guppy and run:
await User.create({ username: 'user' });
It will fail validation. However, if we try:
await User.create({ username: 'user ' });
With a trailing space, it might pass because spaces are considered valid characters. This means you should always trim input values to avoid unintended bypasses.
But aside from that, it works flawlessly. If we pass in a username like "dominus"
, it should work as expected.
So that is the isNotIn
validation rule and how you can use it as a blacklist. It can be useful for filtering restricted words in usernames, chat applications, or any text input. The sky is the limit with this one—you can use it anywhere you need to block certain words.
Full Course
USD