使用hapi / Joi进行Express JS表单验证无法正确验证表单数据

时间:2019-05-03 20:46:22

标签: javascript express ejs

我有一个要使用hapi / Joi包进行验证的表单,但是它不从表单中获取值。相反,它返回第一个验证错误,因为所有架构键都采用“ undefined”的值。我怎么解决这个问题?还有没有一种方法可以在不刷新Express页面的情况下向用户输出错误?如果是,请告诉我。

我的Express代码:

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const Joi = require('@hapi/joi');
const uuidv4 = require('uuid/v4');

app.set('view engine','ejs');

const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname + '/public')));

app.get('/',(req,res)=>{
    res.render('main');
});

const schema = Joi.object().keys({
    name: Joi.string().min(3).required(),
    surname: Joi.string().min(5).required(),
    age: Joi.number().integer(),
    email: Joi.string().email({minDomainSegments: 2}).required(),
    password: Joi.string().min(3).required(),
    confirm: Joi.any().valid(Joi.ref('password'))
});

app.post('/register',(req,res)=>{
    req.body.id = uuidv4();
    console.log(req.body);
    const result = Joi.validate({

        name: req.body.name,
        surname: req.body.surname,
        age: req.body.age,
        email: req.body.email,
        password: req.body.password,
        confirm: req.body.confirm

    }, schema,(error,value)=>{
        if(error){

            printError(error);

        }
        else{
            console.log('success');
        }
    });

});

function printError(error){
    console.log(error);
}

app.listen(3000);

我的表单:

<form action="/register" method="POST" enctype="multipart/form-data">

        <input type="text" name='name' class="form-control" value="">
        <input type="text" name='surname' class="form-control" value="">
        <input type="number" name='age' class="form-control" value="">
        <input type="email" name='email' class="form-control" value="">
        <input type="password" name='password' class="form-control">
        <input type="password" name='confirm' class="form-control">
        <input type="submit" class="btn btn-block btn-success" value="OKAY">

    </form>

我得到的错误:

{ ValidationError: child "name" fails because ["name" is required]
    at Object.exports.process (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\errors.js:202:19)
    at internals.Object._validateWithOptions (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\types\any\index.js:763:31)
    at module.exports.internals.Any.root.validate (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\index.js:145:23)
    at app.post (C:\xampp\htdocs\express+mongo\index.js:31:24)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
    at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:335:12)
  isJoi: true,
  name: 'ValidationError',
  details:
   [ { message: '"name" is required',
       path: [Array],
       type: 'any.required',
       context: [Object] } ],
  _object:
   { name: undefined,
     surname: undefined,
     age: undefined,
     email: undefined,
     password: undefined,
     confirm: undefined },
  annotate: [Function] }

即使我在表单中填写名称输入并按Enter键,它也会显示“必须输入名称”。

1 个答案:

答案 0 :(得分:1)

更改

const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(express.json());
app.use(express.urlencoded({ extended: true }));