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

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

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

问题

  1. const productSchema = new mongoose.Schema({
  2. title: {
  3. type: String,
  4. required: [true, 'A product must have a Title Bro...'],
  5. trim: true,
  6. validate: [validator.isAlphanumeric, '只有字符被接受'],
  7. maxlength: [50, '标题必须少于或等于50个字符'],
  8. minlength: [5, '标题必须多于或等于5个字符']
  9. }
  10. })
英文:

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.

  1. const productSchema = new mongoose.Schema({
  2. title: {
  3. type: String,
  4. required: [true, 'A product must have a Title Bro...'],
  5. trim: true,
  6. validate: [validator.isAlphanumeric, 'only characters are accepted'],
  7. maxlength: [50, 'the title must have less or equal than 50 characters'],
  8. minlength: [5, 'the title must have more or equal than 5 characters']
  9. }
  10. })

答案1

得分: 1

在Mongoose中,您可以使用内置的验证器来验证模式中的字段。要实现您的要求,即检查字段是否包含字母数字字符和空格,您可以使用match验证器与正则表达式。以下是如何操作:

假设您有一个名为User的模型的模式,并且您希望验证用户名字段仅包含字母数字字符和空格,以下是如何使用Mongoose定义模式的示例:

  1. const mongoose = require('mongoose');
  2. const userSchema = new mongoose.Schema({
  3. username: {
  4. type: String,
  5. required: true,
  6. unique: true,
  7. match: /^[A-Za-z0-9\s]+$/, // 正则表达式,允许字母数字字符和空格
  8. },
  9. // 其他字段...
  10. });
  11. const User = mongoose.model('User', userSchema);
  12. 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:

  1. const mongoose = require('mongoose');
  2. const userSchema = new mongoose.Schema({
  3. username: {
  4. type: String,
  5. required: true,
  6. unique: true,
  7. match: /^[A-Za-z0-9\s]+$/, // Regular expression to allow alphanumeric characters and spaces
  8. },
  9. // other fields...
  10. });
  11. const User = mongoose.model('User', userSchema);
  12. 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:

确定