Validation rules
isInteger
Summary
By default, Sails allows any numeric value for attributes of type number
, including decimals. However, some attributes, like age
, should only accept whole numbers. To enforce this, you can use the isInteger
validation rule.
Setting isInteger: true
ensures that only integer values are accepted for a given number attribute. If a decimal number is provided, Sails will reject the input and return a validation error. This rule applies only to attributes of type number
, as it wouldn't make sense for non-numeric types.
In practice, attempting to create a user with an age of 4.5
results in an error, while an age of 23
is accepted. This validation helps maintain data integrity when working with whole-number attributes.
Transcript
Okay, so let's look at our next validation rule. Now, if I go to Visual Studio Code right now, let me just open up Visual Studio Code.
And in our User
model, you could see we have this age
attribute, right? And the type we specify—it says it's going to be a number. And of course, age should be a whole number, right? We don’t want decimals. But with this definition currently, there's nothing that would stop a user from passing in a number like maybe 4.5
or any sort of numbers like that. So how do we add a constraint to this number type that says we only accept integer whole numbers? That brings us to the isInteger
validation rule. Now, this rule is simple. All you have to do is add isInteger
like so
and set it to true
. Now, whenever we're going to pass in a number,
Sails will validate that the number being passed is an integer. And it’s worthy of note that this isInteger
validation will only apply to the number
data type—which makes sense, right? Because you can only validate if a number is an integer. So let's see this in action. I'm opening Guppy right now.
If I do await User.create
, I do lastName: "Godric"
,
firstName: "Griffin"
,
And if I say age
, now let's test out the validation rule. If I do age: 4.5
, let's fetch it. I try to run it. We get an error, right? Which says:
"Could not specify age because 4.5 was not an integer."
So you can see how that's handy. However, if we set this to something like 23
and run this—yeah, you can see we have another validation kicking in, which we set in our last lesson, which is the email. So we do need to specify an email. If we do email: "godric@example.com"
, this should run, and we have that.
So I should disable that required setting on the email. This email is now optional, and there's no need for the allowNull
, because without specifying the allowNull
attribute, it defaults to false
.
So there you have it. That’s it. If you need to make sure that an attribute gets an integer number, you use the isInteger
validation rule.
Full Course
USD