> For the complete documentation index, see [llms.txt](https://hemantajax-2.gitbook.io/mongoose-step-by-step/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hemantajax-2.gitbook.io/mongoose-step-by-step/validation.md).

# 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

```javascript
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

```javascript
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

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

## Custom Validators

```javascript
// 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](https://1650180451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7_vQvwS_k9ryuCEiXL%2Fsync%2Ffc0f5c9acf8590628f6574a5cf8ba5dd9155e551.png?generation=1589774293152944\&alt=media)

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