1
0

Video 85: Data Validation and Sanitization: Part I

This commit is contained in:
JayWll 2020-02-22 14:28:47 -07:00
parent 72d2114a6c
commit 3bd2ece69b
3 changed files with 45 additions and 19 deletions

View File

@ -183,6 +183,11 @@
"requires": {
"memory-pager": "^1.0.2"
}
},
"validator": {
"version": "10.9.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-10.9.0.tgz",
"integrity": "sha512-hZJcZSWz9poXBlAkjjcsNAdrZ6JbjD3kWlNjq/+vE7RLLS/+8PAj3qVVwrwsOz/WL8jPmZ1hYkRvtlUeZAm4ug=="
}
}
}

View File

@ -11,6 +11,7 @@
"license": "ISC",
"dependencies": {
"mongodb": "^3.1.10",
"mongoose": "^5.3.16"
"mongoose": "^5.3.16",
"validator": "^10.9.0"
}
}

View File

@ -1,4 +1,5 @@
const mongoose = require('mongoose')
const validator = require('validator')
mongoose.connect('mongodb://localhost:27017/task-manager-api', {
useNewUrlParser: true,
@ -7,11 +8,41 @@ mongoose.connect('mongodb://localhost:27017/task-manager-api', {
const User = mongoose.model('User', {
name: {
type: String
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
age: {
type: Number
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a positive number')
}
}
}
})
const me = new User({
name: ' Jason ',
email: 'J@SON-WILLIAMS.CA '
})
me.save().then(() => {
console.log(me)
}).catch((error) => {
console.log('Error!', error)
})
const Task = mongoose.model('Task', {
@ -23,24 +54,13 @@ const Task = mongoose.model('Task', {
}
})
const task = new Task({
description: 'Learn the Mongoose library',
completed: false
})
task.save().then(() => {
console.log(task);
}).catch((error) => {
console.log('Error!', error)
})
// const me = new User({
// name: 'Jason',
// age: 'Mike'
// const task = new Task({
// description: 'Learn the Mongoose library',
// completed: false
// })
//
// me.save().then(() => {
// console.log(me)
// task.save().then(() => {
// console.log(task);
// }).catch((error) => {
// console.log('Error!', error)
// })