Go to User.js
User.prototype.register = function(){
// 1. Validate
this.validate()
// 2. Only if there are not validation errors, then save user data into db
}
Create new function above
User.prototype.validate = function() {
if(this.data.username == ""){this.errors.push("You must provide a username")}
if(this.data.email == ""){this.errors.push("You must provide an email")}
if(this.data.password == ""){this.errors.push("You must provide a password")}
}
In the constructor let's create an array to store these errors
let User = function(data){
this.data = data
this.errors = []
}
Test this out
Save the model file
Go to userController.js
Focus on this function:
exports.register = function(req, res){
let user = new User(req.body)
res.send("Thanks for trying to register.")
}
Delete this line
res.send("Thanks for trying to register.")
if(user.errors.length){
res.send(user.errors)
} else {
res.send("Congrats. No errors.")
}
Test this
Add more checks in the model
password should be atleast 12 chars long
this.data.password.length > 0 && this.data.password.length < 12
password cannot exceed 100 chars
username length copy the last two lines - > 0 && < 3 max length should be 30
npm install validator
npm run watch
At the top of the model import this
const validator = require('validator')
Second validation
if(!validator.isEmail(this.data.email)){push error}
Test this
Above the email line add new line
if(this.data.username != "" && !validator.isAlphanumeric()) {push error}
Username can only contain letters or numbers.
Test this.