Skip to main content
Version: Next

Custom Validation

Custom Validation

You can create custom validation rules using the customValidator function. Below is an example of how to define a custom validation rule:

[
{
key: "username",
type: "custom-function",
customValidator: (value) => {
if (!/^[a-zA-Z0-9]+$/.test(value)) {
return "Username should only contain alphanumeric characters";
}
return null; // Return null if validation passes
},
},
];

Explanation

  • key: "username"specifies the field in the request body that you want to validate.
  • type: "custom-function" indicates that a custom validation function will be used.
  • customValidator: This is a function that takes the value to be validated as its argument. The function should return an error message if validation fails, or null/undefined if the validation passes.

In this example:

The customValidator function ensures that the username field contains only alphanumeric characters. If the value does not match the pattern /^[a-zA-Z0-9]+$/, the function returns an error message: "Username should only contain alphanumeric characters". If the value is valid, nothing will returned, indicating no error.