Locked video

Please purchase the course to watch this video.

Buy Now

Validation rules

isIn

Summary

The isIn validation rule in Sails ensures that an attribute can only take values from a predefined list. This makes it perfect for handling fields like user roles, where only specific values should be accepted.

For example, instead of allowing any string for a role attribute, you can define an explicit set of allowed values, such as "user", "admin", and "super-admin". If a value outside this list is provided, Sails will return an error.

A great benefit of isIn is that it also serves as documentation—anyone looking at the model can immediately see the permitted values. Additionally, you can pair it with defaultsTo to ensure a fallback value when none is provided. This prevents errors while maintaining controlled input.

Transcript

Let's look at one of my favorite validation rules in Waterline and Sails.

If we go back to Visual Studio Code, you can see we have an isAdmin attribute, which can be true or false. But what if your application is more complex? What if you have multiple roles and need to enforce strict role assignment?

One way to do this is by using the isIn validation rule to define an array of allowed values. Let's rename this attribute to role and change the type to string:

role: {
  type: 'string',
  isIn: ['user', 'admin', 'super-admin']
}

Unlike other validations that take true or false, isIn requires an array containing the only values that should be allowed.

For example, if your app has user roles "user", "admin", and "super-admin", this ensures that no other values can be set.

One of the reasons I love this rule is that it also serves as documentation. Anyone looking at your model will immediately know what values are permitted.

Now, let's test this in Guppy:

await User.create({ role: 'random-role' });

We get an error because "random-role" is not in our whitelist. Sails checks whether the provided value exists in the list, and if it doesn’t, it rejects the request and displays the allowed values for reference.

If we try:

await User.create({ role: 'super-admin' });

It works fine because "super-admin" is on our list of valid values.

This rule is very convenient when you need to restrict input to a fixed set of options. If an attribute should only accept specific values, isIn should be your go-to validation rule.

Another best practice is to pair isIn with defaultsTo:

role: {
  type: 'string',
  isIn: ['user', 'admin', 'super-admin'],
  defaultsTo: 'user'
}

This means if no value is provided, it defaults to "user". It prevents validation errors and ensures that users always get a predefined role unless explicitly assigned a different one.

isIn is most commonly used with strings, and that's likely where you'll need it the most.

Full Course

$
34.99

USD

plus local taxes
Buy Now