Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Custom validations


We can also add custom validations in case the default built-in validations are not enough.


We can pass a validate function and write our custom code into that function. Let's look


at an example:


var userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: '{VALUE} is not a valid phone number!'
}
}
});

Here, we have passed a validate method to the Schema. It takes a validator function


where we can add our own code for the validation. The preceding method checks if the
phone number field of the user is in the correct format or not. If it does not pass the


validation, then it displays the message {value} is not a valid phone number.


We can also add nested validations in Mongoose: for example, if the name in our user


collection is saved as { name: { first_name: 'Anita', last_name: 'Sharma' } },


we will need to add validations for both first_name and last_name. To do that, we can


use:


var nameSchema = new Schema({
first_name: String,
last_name: String
});

userSchema = new Schema({
name: {
type: nameSchema,
required: true
}
});

First, we define the Schema for a low-level object, which is first_name and last_name.


Then, for the userSchema, we pass on the nameSchema for the name field.

Free download pdf