【发布时间】:2022-05-03 13:49:08
【问题描述】:
const Validator = require("validator");
const isEmpty = require("../validation/is-empty");
module.exports = function validateRegisterInput(data) {
let errors = {};
data.name = !isEmpty(data.name) ? data.name : " ";
data.email = !isEmpty(data.email) ? data.email : " ";
data.password = !isEmpty(data.password) ? data.password : " ";
data.password2 = !isEmpty(data.password2) ? data.password2 : " ";
if (!Validator.isLength(data.name, { min: 3, max: 30 })) {
errors.name = "Name must be between 3 and 30 characters";
}
if (Validator.isNumeric(data.name)) {
errors.name = "No numbers please!";
}
if (Validator.isEmpty(data.name)) {
errors.name = "Cannot be empty!";
}
if (Validator.isEmpty(data.email)) {
errors.email = "Cannot be empty!";
}
if (Validator.isEmail(data.email)) {
errors.email = "Email is invalid!";
}
if (Validator.isEmpty(data.password)) {
errors.password = "Cannot be empty!";
}
if (Validator.isLength(data.password, { min: 6, max: 30 })) {
errors.password = "Password must be between 6 and 30 characters!";
}
if (Validator.isEmpty(data.password, data.password2)) {
errors.password2 = "Passwords must match!";
}
if (Validator.equals(data.password2)) {
errors.password2 = "Cannot be empty!";
}
return {
errors,
isValid: isEmpty(errors),
};
};
大家好!
我正在尝试添加验证,以确保您不能为姓名、电子邮件和密码提交空字符串,但我收到 TypeError: Cannot create property 'ignore_whitespace' on string ' '
TypeError: Cannot create property 'ignore_whitespace' on string ' '
at merge (\node_modules\validator\lib\util\merge.js:14:16)
at Object.isEmpty (\node_modules\validator\lib\isEmpty.js:20:32)
at validateRegisterInput (\config\validation\register.js:33:17)
at router.post (\routes\api\users.js:24:31)
at Layer.handle [as handle_request] (\node_modules\express\lib\router\layer.js:95:5)
at next (\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (\node_modules\express\lib\router\layer.js:95:5)
at node_modules\express\lib\router\index.js:281:22
at Function.process_params (\node_modules\express\lib\router\index.js:335:12)
at next (\node_modules\express\lib\router\index.js:275:10)
at Function.handle (\node_modules\express\lib\router\index.js:174:3)
at router (\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (\node_modules\express\lib\router\index.js:317:13)
at node_modules\express\lib\router\index.js:284:7
我在这里错过了什么?
当我使用 Postman 发出 POST 请求时收到错误消息。
【问题讨论】:
-
你在哪一行得到错误?
-
@phyyyl 我刚刚用完整的错误详细信息更新了帖子。
-
对给定的信息还不能理解。你的文件叫什么?变量“数据”是什么样的?
-
问题可能在于将验证与约束区分开来。请分享您的模型定义以提供更多背景信息。
标签: javascript mongodb express validation mongoose