英文:
how to use validator in mongoose for checking a field to have isAlphanumeric and space
问题 {#heading}
const productSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'A product must have a Title Bro...'],
trim: true,
validate: [validator.isAlphanumeric, '只有字符被接受'],
maxlength: [50, '标题必须少于或等于50个字符'],
minlength: [5, '标题必须多于或等于5个字符']
}
})
英文:
I want to make sure if a field in the model, only have Alphanumeric and space.
I'm using validator.js in the mongoose.
this is what i tried but does not accept space in the field.
const productSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'A product must have a Title Bro...'],
trim: true,
validate: [validator.isAlphanumeric, 'only characters are accepted'],
maxlength: [50, 'the title must have less or equal than 50 characters'],
minlength: [5, 'the title must have more or equal than 5 characters']
`}
})
`
答案1 {#1}
得分: 1
在Mongoose中,您可以使用内置的验证器来验证模式中的字段。要实现您的要求,即检查字段是否包含字母数字字符和空格,您可以使用match验证器与正则表达式。以下是如何操作:
假设您有一个名为User的模型的模式,并且您希望验证用户名字段仅包含字母数字字符和空格,以下是如何使用Mongoose定义模式的示例:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
match: /^[A-Za-z0-9\s]+$/, // 正则表达式,允许字母数字字符和空格
},
// 其他字段...
});
const User = mongoose.model('User', userSchema);
module.exports = User;
英文:
In Mongoose, you can use the built-in validators to validate fields in your schema. To achieve your requirement of checking whether a field contains alphanumeric characters and spaces, you can use the match validator with a regular expression. Here's how you can do it:
Assuming you have a schema for a model named User, and you want to validate the username field to contain only alphanumeric characters and spaces, here's an example of how you can define your schema using Mongoose:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
match: /\^\[A-Za-z0-9\\s\]+$/, // Regular expression to allow alphanumeric characters and spaces
},
// other fields...
});
const User = mongoose.model(\'User\', userSchema);
`module.exports = User;
`