如何在Mongoose中使用验证器来检查字段是否包含字母、数字和空格。

huangapple go评论139阅读模式
英文:

how to use validator in mongoose for checking a field to have isAlphanumeric and space

问题

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

在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;

huangapple
  • 本文由 发表于 2023年8月11日 00:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定