Writing custom validators for Mongoose's schemas

Mongoose has several built-in validation rules. For instance, if you define a property with a schema type of string and set it as required, two validation rules will be executed, one that checks for the property to be a valid string and another one for checking that the property is not null or undefined.

Custom validation rules and custom error validation messages can also be defined in Mongoose for having more control on how and when certain properties are accepted before they can be saved in the database.

Validation rules are defined in the schema. All schema types have a built-in validator required which means it cannot contain undefined or null values. The required validator can be of type boolean, a function, or an array. For example:

      path: { type: String, required: true } 
      path: { type: String, required: [true, 'Custom error message'] } 
      path: { type: String, required: () => true } 

String schema types have the following built-in validators:

  • enum: This states that the string can only have the value specified in the enum array. For instance:
      gender: { 
      type: SchemaTypes.String, 
      enum: ['male', 'female', 'other'], 
      } 
  • match: This uses RegExp to test the value. For instance, to allow values that start with www:
      website: { 
      type: SchemaTypes.String, 
      match: /^www/, 
      } 
  • maxlength: This defines the maximum length that a string can have.
  • minlength: This defines the minimum length that a string can have. For instance, to allow only strings between 5 and 20 characters:
      name: { 
      type: SchemaTypes.String, 
      minlength: 5, 
      maxlength: 20, 
      } 

Number schema types have two built-in validators:

  • min: This defines the minimum value that a number can have.
  • max: This defines the maximum value that a number can have. For instance, to allow only numbers between 18 and 100:
      age: { 
      type: String, 
      min: 18, 
      max: 100, 
      } 
Undefined values pass all validators without error. If you want to throw an error if a value is undefined, do not forget to use the required validator to true

When built-in validators sometimes do not satisfy your requirements or you wish to perform complex validation rules, you have an option or property called validate. This accepts an object that has two properties, validator and message, that allow us to write custom validators:

      nickname: { 
      type: String, 
      validate: { 
      validator: function validator(value) { 
      return /^[a-zA-Z-]$/.test(value) 
      }, 
      message: '{VALUE} is not a valid nickname.', 
      }, 
      } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.18