我在 Node.js 项目中使用建议的 Express-validator V4 语法:
const { check, validationResult } = require('express-validator/check');
const { matchedData } = require('express-validator/filter');
Run Code Online (Sandbox Code Playgroud)
和
app.post('/users/add/',[
check('first_name')
.isLength({ min: 1 }).withMessage('A first name is required')],
(req, res, next) => {
var errors = validationResult(req);
if (errors) {
..etc
Run Code Online (Sandbox Code Playgroud)
请注意,我使用的是现代语法,并且没有以下代码(根据express-validator README.md 文件):
const expressValidator = require('express-validator');
app.use(expressValidator());
Run Code Online (Sandbox Code Playgroud)
在运行验证之前如何修剪输入字段中的空格?
我一直在使用 expressjs 开发应用程序,但在使用 express-validator V4 时出现错误。错误是:
TypeError: check is not a function
所以我的代码看起来像这样:
//users.js
var check = require('express-validator/check');
var validationResult = require('express-validator/check');
router.post('/register',[
check('name').exists()
], function(req, res){
var errors = validationResult(req);
if(errors){
console.log('There are errors');
}else{
console.log('No errors');
};
});
module.exports = function(app){
app.use('/users', router);
};
Run Code Online (Sandbox Code Playgroud)
请注意,我使用的是纯 javascript,没有 ES6。谢谢。
在将其标记为重复之前,请理解我所查看的答案都与我的代码无关,无法解决问题。我正在尝试修复 Web 应用程序中的错误,该应用程序正在将文件从 Internet 上传到家庭服务器。我目前正在研究基本的用户身份验证系统。当我尝试在主页上提交登录表单时,我被重定向到一个错误页面,其中部分内容显示“无法读取未定义的属性‘用户名’”。此消息也出现在控制台中。发生了什么,我该如何解决?该错误将我引导至家庭控制器的第 8 行,“username = req.body.username”。应用程序.js
var LocalStrategy = require('passport-local').Strategy;
var flash = require("connect-flash");
var passport = require("passport");
var session = require("express-session");
var expressValidator = require("express-validator");
var mongoose = require("mongoose");
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
var ejs = require('ejs');
var routes = require('./server/routes');
routes(app);
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser());
mongoose.connect("mongodb://localhost:27017/users");
app.listen(app.get('port'), …Run Code Online (Sandbox Code Playgroud) 我在使用快速验证器时遇到了问题,特别是 isDate 函数。我已采取措施使用 expressvalidator、bodyparse、validator 模块等。所有路由仅在此之后.. 环境是 Node + Express。
问题在于使用
"req.checkBody('date_of_birth', 'Invalid date').optional({ checkFalsy: true }).isDate();"
Run Code Online (Sandbox Code Playgroud)
我不断收到以下错误。
TypeError: req.checkBody(...).optional(...).isDate is not a function
at exports.author_create_post (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/controllers/authorController.js:47:81)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at /Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:174:3)
at router (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:317:13)
at /Users/svitaworld/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
at /Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:635:15
Run Code Online (Sandbox Code Playgroud)
应用程序.js
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ …Run Code Online (Sandbox Code Playgroud) 我正在使用“ express-validator”中间件来验证表单。因为我使用的是模式验证,所以我有一些异步任务可以验证,第一个是电子邮件验证,第二个是用户名验证。我如何正确地工作取得了一些进展。
但是我无法根据不同的情况设置适当的错误消息。因此,当您查看我的代码(当来自DNS的电子邮件无效时)时,它应显示“不是有效的电子邮件”,但始终显示“此电子邮件已在使用中”(与用户名字段相同)。当我不输入任何内容时,用户名错误显示“此用户名已被使用”,当我输入25个以上字符时,显示“请输入用户名”
因此,请指导我如何更正此错误并获取所需的错误消息。
var validation_rules = checkSchema({
company_name: {
errorMessage: 'Company Name should be at least 3 chars long and maximum of 50 chars',
isLength: {
options: { min: 3, max : 50 }
},
trim: true
},
profile_name: {
errorMessage: 'Public Profile Name should be at least 3 chars long and maximum of 50 chars',
isLength: {
options: { min: 3, max: 50 }
},
trim: true
},
description: {
errorMessage: 'Company Description should be at least 2 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 express-validator,但它的功能都不起作用。我也没有收到任何错误。
例子:
const check = require('express-validator/check').check;
router.post('/register', check('someRandomName').exists(), (req, res) => userController.register(req, res));
Run Code Online (Sandbox Code Playgroud)
express-validator 总是允许它,即使我someRandomName在请求中没有。
我也尝试使用body而不是check,但结果是一样的。
我希望用户能够在端点中写入特定的帐号,并尝试验证端点参数是否存在于我的数据库中。我无法让它工作,请问我做错了什么?
我的验证
const validateReq: [
param('accountNumber').exists().custom(acctNo => accountNumberExist(acctNo)),]
Run Code Online (Sandbox Code Playgroud)
我的 accountNumberExist 函数
accountNumberExist(inputAcct) {
const isfound = accounts.find(account => account.accountNumber === inputAcct);
if (isfound === undefined) throw new Error('Account Number not found');
}
Run Code Online (Sandbox Code Playgroud)
我的账户档案
const accounts = [
{
id: 1,
accountNumber: 1234567890,
createdOn: new Date(),
owner: 1,
type: 'current',
balance: 23444.43,
status: 'active',
},
{
id: 2,
accountNumber: 1234167890,
createdOn: new Date(),
owner: 1,
type: 'savings',
balance: 2233444.43,
status: 'active',
},
{
id: 3,
accountNumber: 9987654321,
createdOn: new Date(),
owner: …Run Code Online (Sandbox Code Playgroud) 如果单击该复选框,我会尝试将Display Name用户的 设为可选。Anonymous
为此,我正在使用express-validator.
检查以下代码:
router
.route("/create-checkout-session")
.post(
[
check("displayName") //if isAnonymous : true than this is optional
.matches(vars.intlRegex)
.trim()
.escape()
.withMessage("Please provide a display name")
.optional({ checkFalsy: true }),
check("isAnonymous").isBoolean()],//isAnonymous
checkForErrors,
createCheckoutSession
Run Code Online (Sandbox Code Playgroud)
如何在一个字段中验证另一字段的值,并据此将其设为可选。
提前致谢
我用作handlebar page模板和nodejs后端。
condtional validation if (a < b)我想在网页上使用然后显示错误消息。但我无法这样做express-validators。
这是我下面的代码,我正在尝试它不起作用。我'lt'确实使用了 2 个字母关键字=,但它不起作用。
router.post('/addtasks', function(req, res, next) {
req.checkBody('topic', 'Empty Topic').notEmpty();
req.checkBody('website', 'Empty Website').notEmpty();
req.checkBody('words', 'Empty Words').notEmpty().isLength({ min: 3 }).isInt({ lt: 2000});
});
Run Code Online (Sandbox Code Playgroud)
他们first 2正在网页上抛出错误消息。但它3rd one不起作用。我还可以实现这一目标any other way 吗express package?谢谢!
编辑我正在尝试的内容:
router.post('/addtasks', function(req, res, next) {
req.checkBody('topic', 'Empty Topic').notEmpty();
req.checkBody('website', 'Empty Website').notEmpty();
var totalCount = 2000;
totalCount = totalCount - 500;
req.checkBody('words', 'Empty Words or Min. …Run Code Online (Sandbox Code Playgroud) 在前端使用 JavaScript,我创建了正则表达式,它允许字母、数字和一些特殊字符,例如......
function onlyAlphaSomeChar(value) {
const re = /^[A-Za-z0-9 .,'!&]+$/;
return re.test(value);
}
Run Code Online (Sandbox Code Playgroud)
如果我要在后端使用express-validator构建验证过程,那么这相当于什么?
我在 ExpressJs 环境中创建了这么多,但不确定下一步应该是什么样子......
//...
app.post('/', [
//VALIDATE
check('comment')
.notEmpty()
.withMessage('Comment required')
.isLength({min: 3,max:280})
.withMessage('Comment must be between 3 and 280 characters')
.escape()
], (req, res) => {
//...
});
Run Code Online (Sandbox Code Playgroud)