# 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](/files/-M7_v_ZXABBgm7q0zXby)

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hemantajax-2.gitbook.io/mongoose-step-by-step/validation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
