Validation

Built-in Validators

Schema-Type

Built-in Validators

String

required

enum

match

Number

required

min

max

Date

required

Buffer

required

Boolean

required

Mixed

required

ObjectId

required

Array

required

Strings - Required

var customerSchema = new Schema({ 
    name: { type: String, required: true }
});

// OR
// After the schema is defined – via the path API 
// Signature = required(required, [message])
customerSchema.path(‘city’).required(true, ‘Oops! Supply a city.’);

Strings – Match and Enum

var customerSchema = new Schema({ 
    name: { type: String, required: true, match: /[a-zA-Z]/ }
});

var customerSchema = new Schema({ 
    name: { type: String, required: true, enum: [‘none’, ’minor’, ’blocking’, ’severe’] }
});

Numbers Validation

var customerSchema = new Schema({ 
    discount: { type: Number, required: true,  min: 5, max: 60 }
});

Custom Validators

// Custom validation – method signature = validate(obj, [errorMsg]) 
var sizeValidator = [ 
    function (val) { 
        return (val.length > 0 && val.length <= 50) 
    }, 
    'String must be between 1 and 50 characters long' 
];

var personSchema = new Schema({ 
    firstName: { type: String, required: true, validate: sizeValidator }
});

Overwrite In-built validation

Overwrite Inbuilt validation
// return validation error `errMsg`
res.render('index', { title: 'Page Title Here', message: errMsg });

Last updated

Was this helpful?