Getting Started
Installing Superstruct
To install Superstruct run:
And then you can import it:
If you'd like, you can use a wildcard import:
If you'd rather use a <script>
tag, you can use the UMD build:
This will expose the Superstruct
global.
Defining Structs
Once you've got Superstruct installed, the next step is to create a "struct" for some data you want validate. Each struct corresponds to a specific type of data. In our case, lets start with data describing a user:
We'll import Superstruct and create an object-shaped struct with it:
This User
struct will expect an object with an id
property that is a number, and name
and email
properties that are strings.
Now we can use our User
struct to validate the data. The easiest way to do this is to use the assert
helper, like so:
This will throw an error if the data is invalid. In this case, the data is valid, so no error is thrown.
But if we pass it invalid data, it will throw an error:
If you'd rather have the error returned instead of thrown, you can use the validate
helper. Or, if you'd just like receive a boolean of whether the data is valid or not, use the is
helper.
Last updated