Create a Custom Validator in AdonisJS/Node js?

Creating a custom validator in AdonisJS allows you to define your own validation rules that can be used to validate input data in your application. Here’s a step-by-step guide on how to create a custom validator in AdonisJS:

1.Create the Validator:

Start by creating a new custom validator using the AdonisJS command-line tool.

adonis make:validator CustomValidatorTR

Replace CustomValidatorTR with the desired name for your validator.

2.Define Validation Rules:

Open the newly generated validator file located in the app/Validators directory. Inside the file, you can define your custom validation rules using the Validator class.

const { rule } = use('Validator');

class CustomValidatorTR {
  get rules() {
    return {
      // Define your custom rules here
      customRule: [rule('custom_rule')],
    };
  }
}

module.exports = CustomValidatorTR;

3.Create the Custom Validation Rule:

Next, you need to create the actual custom validation rule. Create a new file in the app/Validators/Rules directory (create the Rules directory if it doesn’t exist) with the name of your custom rule, followed by .js. For example, if your rule is custom_rule,

create a file named CustomRule.js.

const { rule } = use('Validator');

rule('custom_rule', async (field, value, args, { error }) => {
  // Implement your custom validation logic here
  if (value !== 'custom_value') {
    throw error('Invalid value for custom_rule validation');
  }
});

4.Using the Custom Validator:

Now that you’ve created your custom validator and rule, you can use it in your application’s validation process.

const { validate } = use('Validator');
const CustomValidatorTR = use('App/Validators/CustomValidatorTR');

const data = {
  customField: 'custom_value', // Replace with actual data
};

const rules = {
  customField: 'custom_rule', // Use your custom rule
};

await validate(data, rules, CustomValidatorTR.messages);

Replace customField with the actual field you want to validate, and custom_value with the value to validate against.

5.Error Messages:

You can define custom error messages for your custom validation rule by adding them to the CustomValidator.messages object. This helps provide clear error messages when validation fails.

That’s it! You’ve successfully created a custom validator and rule in AdonisJS. This process allows you to create and use custom validation rules tailored to your application’s specific needs.

Leave a Comment