ValidatorJS isNumeric函数工作不正常



所以,我想验证一个Mongoose字段,它应该是一个只包含数字的字符串(因为第一个数字可以是0(,我设置了一个自定义验证器,比如:

id: {
type: String,
required: [true, REQUIRED_VALIDATOR_ERROR_MESSAGE("ID")],
validator: {
validate: (value: string) => validator.isNumeric(value),
message: (props) => `${props.value} is invalid.`,
},
}

但当我传递一个包含字母的ID时,验证就通过了。

您将validatevalidator混合在一起。应该是:

id: {
type: String,
required: [true, REQUIRED_VALIDATOR_ERROR_MESSAGE("ID")],
validate: {
validator: (value: string) => validator.isNumeric(value),
message: (props) => `${props.value} is invalid.`,
},
}

下面是一个最小的工作示例:

const mongoose = require("mongoose");
const validator = require("validator");
mongoose.connect("mongodb://localhost/test", { useNewUrlParser: true });
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", async function () {
await mongoose.connection.db.dropDatabase();
// we're connected!
console.log("Connected");
const userSchema = new mongoose.Schema({
friends: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
name: String,
pid: {
type: String,
required: true,
validate: {
validator: function (value) {
console.log("TEEEST", value);
return validator.isNumeric(value);
},
message: (props) => "Prop is invalid",
},
},
});
const User = mongoose.model("User", userSchema);
const bob = new User({ name: "Bob", friends: [], pid: "0123" });
await bob.save();
const natalie = new User({ name: "Natalie", friends: [bob], pid: "23" });
await natalie.save();
//const chris = new User({ name: "Chris", friends: [] });
//await chris.save();
const john = new User({ name: "John", friends: [natalie, bob], pid: "abc" });
var valres = john.validateSync();
console.log(valres);
await john.save();
});

参考:https://mongoosejs.com/docs/4.x/docs/validation.html,自定义验证器

最新更新