我对节点和表达还比较陌生,遇到了一个我似乎无法解决的问题。
我创建了一个SSCCE,它尝试接受两个输入,即名称和高度,如果存在验证错误,请使用这些值再次渲染同一页面。
如果我在“高度”字段中输入“ 2.2.2”(显然不是浮点数),则不会重新渲染该值。如果我将输入的高度更改为type =“ text”,则该字段将使用先前的值进行渲染。文本类型的所有其他字段的行为均符合预期。
我在表格上输入了“ novalidate”,但这是数字输入类型的怪癖吗?还是我犯了一个简单的错误?
(关于'isFloat()'为何接受'2'为有效位,我也有些困惑)
任何帮助将不胜感激
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { check } = require('express-validator/check');
const { validationResult } = require('express-validator/check');
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get('/', (req, res, next) => {
res.render('test', {
pageTitle: 'Test',
hasError: false,
validationErrors: []
})
});
app.post('/',
[
check('name', 'Name must be at least 2 letters in length')
.isLength({min: 3}),
check('height', 'Height must be a float')
.isFloat()
] ,
(req, res, next) => {
const errors = validationResult(req);
if(!errors.isEmpty()){
console.log(errors.array());
return res.render('test', {
pageTitle: 'Error',
hasError: true,
validationErrors: errors.array(),
person: {
name: req.body.name,
height: req.body.height
}
})
} else {
res.send(`Person created: ${req.body.name}, height: ${req.body.height}`);
}
});
app.listen(3000);
test.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= pageTitle %></title>
</head>
<body>
<div class="errorMessage"><%= validationErrors.length > 0 ? validationErrors[0].msg:'' %></div>
<form action="/" class="test-form" method="POST" novalidate>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<%= hasError ? person.name:'' %>">
<label for="height">Height</label>
<input type="number" name="height" id="height" value="<%= hasError ? person.height:'' %>">
<button class="submit">Submit</button>
</form>
</body>
</html>
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.6.1",
"express": "^4.16.4",
"express-validator": "^5.3.1"
}
}
答案 0 :(得分:0)
我放弃了。即使没有novalidate,似乎也没有任何办法让数字类型的输入字段提交无效值。
所以我只是将类型更改为文本。