简体   繁体   中英

How can I check if password is the same as confirmed password before saving the input into database (mongoose + express + validator)

server.js

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)

interface:

在此处输入图像描述

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

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. By the way express validator also supports client-side validation. 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)

You can do it in app.post('/) route.

before passing the data to new Account() , you might get the values by doing this.

const {password, cfpassword} = req.body;

Then call the validator 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM