Before adding data to the database, one has to make sure the data is valid, because if it is not it can lead to huge consequences down the road. To do that in Sequelize we can use validations and constraints.
The difference between validations and constraints
Validations are done by the Sequelize framework on the JavaScript level. We can provide custom validator functions or use predefined validators for this. If our data fails this validation then no SQL query will be made.
Constraints are the rules that we define on the level of SQL. For example, if one attribute is supposed to be unique then this will be handled on the level of SQL. If a constraint check fails then Sequelize will forward the error message sent by the database. Here an SQL query will be performed no matter what.
Let’s start by setting up a project. If you don’t know how to work with Sequelize or need help setting up the project you can refer to one of my previous articles here.
We will be working with the user’s table.
For now, my folder looks like this.
Now create user.js in the models folder and paste the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
'User', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
username: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING
}
},
);
return User;
};
For now, we have an ID, username, and password in the user’s table. Now let’s add a unique constraint. This means only unique values can be added to a column.
In the user.js file modify the username key like this.
1 2 3 4
username: { type: DataTypes.STRING, unique: true },
We have added a unique: true key-value pair.
Let’s run the server now. Type nodemon index.js in the terminal. You will see the following query in the terminal:
You can see that the unique constraint has been added in the query.
Let’s see it in action. Add the following API in index.js
1 2 3 4 5 6 7 8
app.post("/", async (req, res) => { try { const user = await db.User.create(req.body); res.send(user); } catch (err) { res.send(err); } });
Here we are adding the data from the request body to the user. Make a request using postman and send the following data in the request body.
1 2 3 4
{ "username": "Srajan", "password": "devPassword" }
You will get the following response.
1
2
3
4
5
6
7
{
"id": 1,
"username": "Srajan",
"password": "devPassword",
"updatedAt": "2021-11-22T12:40:28.122Z",
"createdAt": "2021-11-22T12:40:28.122Z"
}
Note: We never store passwords directly. Now, make the request again. You will get a long error message. Take a look at the following:
We have added a successful constraint to our table. We can also add constraints like allowNull: false, which will stop insertion of null values. We will add this to both the username and password. Now our model looks as follows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
'User', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
},
);
return User;
};
We can have several validations. Validations are written inside of the “validate” object. For example, if you want your username to be in the format of an email, then you can use the following. Modify the username object like this.
1 2 3 4 5 6 7 8
username: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: true } },
Send the following data in the request body.
1 2 3 4
{ "username": "Srajan@gmail.com", "password": "devPassword" }
Now send data that is not in the format of an email.
We get an error.
There are tons of predefined validations in Sequelize. You can see more of the predefined validations here.
You can add custom error messages on validations as well. Modify username objects like this.
1 2 3 4 5 6 7 8 9 10
username: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: { msg: "Must be an EMAIL ##CUSTOM MESSAGE##", }, }, },
Now the error will look like this.