Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Last active November 11, 2020 16:35
Show Gist options
  • Select an option

  • Save tjkhara/b4e75f563c4a8eebb908a27597891d2d to your computer and use it in GitHub Desktop.

Select an option

Save tjkhara/b4e75f563c4a8eebb908a27597891d2d to your computer and use it in GitHub Desktop.
Complex App Note 5 - Adding validation to our model

Adding validation to our model

Part 1

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

Part 2

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

Email validation

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

Check username for weird chars

Above the email line add new line

if(this.data.username != "" && !validator.isAlphanumeric()) {push error}

Username can only contain letters or numbers.

Test this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment