Validation rules
isURL
Summary
In this lesson we looked at how to use the isURL
validation rule in Sails.js to ensure that an attribute intended to store URLs contains only valid URLs. The example focuses on a twitterUrl
attribute in a user model. By default, any string, including an empty string, would be valid, which is undesirable for URL fields. By applying the isURL
validation, Sails ensures that only properly formatted URLs are accepted. The transcript includes a demonstration of how Sails rejects invalid inputs and accepts valid ones.
Transcript
All right, so let's look at another validation rule. I pretty much like this one because I use it quite a lot, even on sailscasts.com.
So let's jump over to my terminal here. And I'm going to just open Visual Studio Code and still on our demo user model. What we're going to do is add a new attribute called twitterUrl
because we want to capture the Twitter URL of the user. And of course, it's going to be of type string.
But I think you might already notice the problem. If the Twitter URL, which is expected to be a URL, is of type string, then any valid string—including an empty string—is going to be valid, which is not what we want. Because of scenarios like that, where we need to capture a URL (like maybe an image URL stored on S3, a LinkedIn URL, or any URL for that matter), Sails comes with the validation rule called isURL
.
Like so. Once I set this to true
, Sails is going to validate that any string given to this twitterUrl
attribute is actually a URL.
And just for consistency with the rest of our attributes, I'm going to put a columnName
. I'm going to give it twitter_url
just for the physical database, the underlying database.
So with this set, now if we go to Guppy and run:
await User.create({ twitterUrl: "someRandomString" });
You’ll see that we get an error:
Invalid new record, Twitter URL violates one or more validation rules.
And now it lists that the input is not a URL. So Sails will check that the string passed is a valid URL before allowing it.
If instead, we do:
await User.create({ twitterUrl: "https://twitter.com/dominuskelvin" });
And run this, yeah, of course, it's a valid URL, so it is accepted.
So that's how to validate a URL in Sails.
Full Course
USD