Locked video

Please purchase the course to watch this video.

Buy Now

Validation rules

isUUID

Summary

In Sails.js, you can validate that a string is a UUID using the isUUID rule. UUIDs are unique identifiers used in databases instead of incrementing integers. They come in versions 1 through 5, but v4 is the best choice for database IDs because it is completely random.

To enforce this validation in a Sails model:

uuid: {
  type: 'string',
  isUUID: true
}

When creating a record, non-UUID strings will be rejected:

await User.create({ uuid: "randomString" }); // Fails
await User.create({ uuid: "550e8400-e29b-41d4-a716-446655440000" }); // Passes

The second segment of a UUID indicates its version (e.g., xxxxxxxx-4xxx-xxxx-xxxx-xxxxxxxxxxxx means v4). While isUUID accepts versions 1–5, v4 is recommended for database IDs.

Transcript

Hey, so let's look at how to validate that a given string is a UUID. If you don’t know what UUIDs are, they’re Universally Unique Identifiers used as IDs in databases. Instead of using incrementing integers, you can opt for UUIDs. I use them a lot—every ID in my applications is a UUID.

We’re going to see how to validate that a given attribute accepts a UUID. In my code editor, I’m still in the user model. Normally, the id field is a UUID, but for demo purposes, I’ll create a new attribute called UUID, set its type to string, and validate it using the isUUID rule.

Over in Guppy, let’s test UUID validation. UUIDs come in versions 1 through 5:

  • v1 & v2: Time-based, using MAC addresses (not ideal because they can generate duplicates).

  • v3 & v5: Deterministic, based on hashing namespaces.

  • v4: Completely random, best for database IDs.

To check a UUID’s version, look at the second segment:

xxxxxxxx-4xxx-xxxx-xxxx-xxxxxxxxxxxx  →  v4 (random)
xxxxxxxx-3xxx-xxxx-xxxx-xxxxxxxxxxxx  →  v3 (namespace-based)

Now, if we test a random string in Guppy:

await User.create({ uuid: "randomString" });

It fails because it’s not a valid UUID.

But if we use a v4 UUID:

await User.create({ uuid: "550e8400-e29b-41d4-a716-446655440000" });

It passes.

The takeaway: while isUUID validates versions 1–5, v4 is the best choice for database IDs. There are npm packages to generate v4 UUIDs, and I highly recommend using them.

Full Course

$
34.99

USD

plus local taxes
Buy Now