I am trying to validate the registration number. It should only be alphanumeric. I don't understand why my validate function is not working. I have attached the schema below.
const mongoose=require('mongoose');
const validator=require('validator');
const dvSchema=new mongoose.Schema({
registrationNumber:{
type:String,
validate(value){
if(!validator.isAlphanumeric(value)){
throw new Error('Registration number should be alphanumeric.')
}
},
unique:true,
required:true,
},
vehicleType:{
type:String,
enum:['bike','truck'],
default:'truck'
},
city:{
type:String,
required:true
},
activeOrdersCount:{
type:Number,
min:0,
max:2,
default:0
}
})
module.exports=mongoose.model('deliveryVehicle',dvSchema);
The format of your validate field is incorrect.
See the documentation on Mongoose.JS under Custom Validators .
Change registrationNumber to the following.
registrationNumber: {
type: String,
validate:
validator: function(value) {
return validator.isAlphanumeric(value);
},
error: 'Registration number should be alphanumeric.'
},
unique:true,
required:true,
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.