[英]How can I check if password is the same as confirmed password before saving the input into database (mongoose + express + validator)
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const validator = require('validator')
mongoose.connect("mongodb://localhost:27017/iServiceDB", { useNewUrlParser: true })
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html")
})
app.post('/', (req, res) => {
const NewAccount = new Account(req.body)
NewAccount.save((err) => {
if (err) { console.log(err) }
else {
res.send("Inserted successfully")
console.log("Inserted successfully")
}
})
})
app.listen(4000, (req, res) => {
console.log("server is running on port 4000")
})
const accountSchema = new mongoose.Schema(
{
fname: {
type: String,
required: true,
},
lname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
index: { unique: true },
validate: [validator.isEmail, 'invalid email'],
},
password: {
type: String,
required: true,
minlength: 8
},
cfpassword: {
type: String,
required: true,
minlength: 8
}
}
)
const Account = mongoose.model('Account', accountSchema)
I am new to this but I am trying to match the password and confirmed password before inserting new data into the database.我是新手,但我试图在将新数据插入数据库之前匹配密码和确认密码。 I have 2 inputs (password and confirmed password in the index.html
我有 2 个输入( index.html
中的密码和确认密码
Is there any method to achieve this goal?有什么方法可以实现这个目标吗?
You can do this in 2 places.您可以在两个地方执行此操作。 I would suggest doing it on the front end as well as that will improve UX.我建议在前端这样做,这样可以改善用户体验。 And of course on the backend, because we don't trust front-end inputs.当然在后端,因为我们不信任前端输入。
If you are using just express js and serving files with that ( Not using libraries like React) then, You might do it on the backend only.如果您只使用 express js 并使用它提供文件(不使用像 React 这样的库),那么您可能只在后端执行此操作。 By the way express validator also supports client-side validation.顺便说一下,express validator 也支持客户端验证。 check docs here.在这里查看文档。
Using Express validator: ( I could not find the way to mention it in a schema like you are doing for other fields)使用 Express 验证器:(我找不到像您在其他领域所做的那样在模式中提及它的方法)
You can do it in app.post('/)
route.你可以在app.post('/)
路线中做到这一点。
before passing the data to new Account()
, you might get the values by doing this.在将数据传递给new Account()
之前,您可能会通过这样做获得值。
const {password, cfpassword} = req.body;
Then call the validator function:然后调用验证器 function:
if (!validator.equals(password, cfpassword)) {
res.status(400).json({ message: 'Reapeat password does not match'});
}
And then do other things what you are doing.然后做你正在做的其他事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.