This time I will talk about how you can validate data with Vapor 2.0. I’ll go through the basics and also how you can use them inside the Model objects. It is important that the users of your service can’t insert invalid data to your system. So, you must always make sure the data provided is in correct format. In Vapor you can do that using the Validator. Validator is a Generic type that represents a piece of data that has been validated.

Validator defines the type of data you want the data to be validated against. For example, OnlyAlphaNumeric validator accepts only alphabetic and numeric input. There is also an email validator which makes sure the data provided is an email address. You can also define your own custom Validator by conforming to Validator protocol. In this post, I’ll show you how you can use them inside your model object, using the FriendService as an example. By the way, FriendService is a good example of not having the data validation correctly set up. It has been running for ~8months now, and without validation, the friend list now has some incorrect data in its variables. I would have been disappointed if it didn’t, so thanks for everyone who has tried it out.

FriendService is an example server-side Swift project. You can create, read, update and delete information about your trusted friends. Incase you want learn more about the service, please click the link above. You can find the source code for the project on GitHub. You can clone or donwload the project if you want, but you can also follow the example code in this blog post. Now, let’s get started!

approved image

Validate data

First, you need to add the validation package to your project. You can do that by using the swift package manager. Open the Package.swift file and add the validation package in it.

You can spot the last package is called validation.git and that will add the Validator to your project. Next run vapor update on your terminal or command line so that vapor fetches the package.

Now that you have the tools setup I assume you are anxious to use them.

Basic validation

At first, let’s test the basic validation straight inside the main.swift file. Create a new onlyAlphaNumeric route which only allows alphabetic and numeric input:

You need to check that param input is available and that it is a string. Otherwise, throw a badRequest error. Next line is the validation. Since the validate() can throw you need to add try in front of it. If the data provided passes the validation, return the provided parameter. Otherwise the route will throw with http-status code 500 “Internal server error”.

You can test this new route by running the application and posting data, for example with Postman. validate passes, if you post a string that only has alphabetic and numeric characters. If you past data that has some special characters validate will throw an error:

Validate failed posting data with Postman

Let’s try another one. Say you have a restriction about the length of the data user can provide. For example, username must be atleast 2 characters long, but less than 41 characters. Here you can use the Count validator. Check the code below to see how to use it:

Create a new route called validateLength, and check that the string provided is 2 or more characters long. Then check agains the maximum length of 40 characters. If the string passes both of these validations return the string back to the caller.

Validate data inside the Model

As you see, the code gets messy really fast if you do the validation inside the routes. That is why it is better to move the validation inside the model class.

Above, you can see the Friend model constructor. What you need to do is to validate all the data provided. First, import Validation to the file so that it is available in Friend model. Now, when you start validating the data, you can do it like this:

Now the firstname provided can only include alphabetics and numerics. If the validation fails, friend is not created and validate throws an error.

But wait a minute! OnlyAlphaNumeric is not the correct validation here. You are absolutely right! Next let’s check how you can create custom Validators.

Validate data with custom data Validator

You can create your custom data validator by confirming the Validator protocol:

I won’t go to protocols with associated type (PAT) since it is not in the scope of this post. If you want to understand it better, checkout this Alexis Gallagers talk about the topic. The thing that is interesting here is the validate function which you need to implement. Check the implementation of OnlyAlphaNumeric validator:

As you can see, first the valid character set is defined at the start of the file. Then inside the OnlyAlphaNumeric struct validate function is defined to conform the Validator protocol. By using this file as an example, it is very easy for you to start creating your own custom validators.

Since I live in Scandinavia, I created a validator that accepts scandinavian names. Checkout how the OnlyScandicAlpha validator looks like:

I changed the character set to only include scandinavian characters. (also include åäö). There rest of the code is completely same, I only changed the comments to match the code.
Now you can use this the same way as OnlyAlphaNumeric. You can also create a PhoneNumberValidator the exact same way. Since the code is pretty boiler plate I won’t paste it in here.

Validate name and phone number

Now, everything is ready. You can add validation for name and phone number inside the Friend model. Add the following 3 lines to the constructor:

The constructor should look like the code above after you added the validators. Please don’t use the phone number validator in production code. It does not apply to all the phone numbers in the world. It was only an example of how you can use custom validators with Vapor 2.0.

 Validate length between certain range

Ok, the last thing you should do is to make sure the data provided is the correct length. You want firstname and lastname to be atleast 2 characters and no more than 40 characters long. You could do it by calling the min and max functions to both of the parameters. But there is also a better way. Here is how you can do it:

Create an instance of Count and name it nameLengthValidator. Count is defined with a Generic type Countable. Because of that, you need to specifically define the input type you are passing is String. Vapor has already conformed String to Countable so you can use it here. Next, use the containedIn function to set the low and high values. These are the minimum and maximum character lengths the string is validated against. If the string does not pass these conditions, an error is thrown. After this you can be sure the data provided is the way you want it to be.

Ok, that was all that I wanted to share in this post. I Hope I was able to help you to understand the exciting world of data validation with Vapor a bit. If you have any questions, post a comment, tweet or send me an email. Thanks for reading and see you soon my friend!