Skip to main content
Version: Next

Rule Definition

Each rule in the rules array is an object with the following properties:

What is Validation Rules?

The rules in the validateRequestBody middleware define a set of criteria used to validate the data in an incoming request body. Each rule specifies conditions that the data must meet to be considered valid. Here’s a detailed breakdown of what these rules are and how they work:

Purpose of Rules

The purpose of these rules is to ensure that the request body of incoming HTTP requests adheres to certain standards and expectations. This helps to prevent errors, ensure data integrity, and enforce consistency across the application.

Components of a Rule

Each rule is an object that contains the following properties:

Validation Rules

NameTypeRequired
keystringYes
typestring or string[]Yes
requiredbooleanNo
minnumber or objectNo
maxnumber or objectNo
regexRegExpNo
customValidatorFunctionNo

Detailed Information

Key

Identifies which field in the request body is being validated.

Type

Specifies the expected data type for the value of the key. The value must match one of the types provided.
Valid types include string, number, boolean, array, object, email, custom-regex, or custom-function.
You can provide a single type or an array of types; validation will succeed if the value matches any of the provided types.

Required

Indicates whether the key is mandatory in the request body. If true, the key must be present; if false or omitted, the key is optional.

Min

Sets the minimum allowed length or value for the key's value. This can be useful for strings, arrays, and numbers. It can also be an object with different minimum values for different types.

Max

Sets the maximum allowed length or value for the key's value. Similar to min, it applies to strings, arrays, and numbers. It can also be an object with different maximum values for different types.

Regex

Defines a regular expression that the value must match if it is a string. Useful for format validation like emails or phone numbers.

Custom Validator

Allows for custom validation logic beyond the built-in types and constraints. The function should return an error message if validation fails or null/undefined if it passes.