Validate username available using express-validator
Writing custom validators for express-
validator
is easy, but to validate that username is not used we should do call to database which is asynchronous. Async validation is a little bit tricky so here we consider it.
First, add a custom validator which returns Promise
:
router.use(expressValidator({
customValidators: {
isUsernameAvailable(username) {
return new Promise((resolve, reject) => {
User.findOne({ username: username }, (err, user) => {
if (err) throw err;
if(user == null) {
resolve();
} else {
reject();
}
});
});
}
}
})
);
Now registration route for the rest endpoint looks next:
// Register User
router.post('/register/', (req, res) => {
const username = req.body.username;
const password = req.body.password;
// Validation
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('username', 'Username already in use').isUsernameAvailable();
req.checkBody('password', 'Password is required').notEmpty();
req.asyncValidationErrors().then(() => {
//no errors, create user
const newUser = new User({
username: username,
password: password,
});
User.createUser(newUser, (err, user) => {
res.json({
status: 'success',
errors: null,
})
console.log("New user:", newUser);
});
}).catch((errors) => {
if(errors) {
return res.json({
success: false,
errors: errors
});
};
});
});