core icon indicating copy to clipboard operation
core copied to clipboard

How can I create a custom rule of validator on Adonis 5.x

Open fershopls opened this issue 5 years ago • 2 comments

I'm using Mongoose for my models and would like to create a custom uniqueMongo rule to make emails of users unique.

I've seen that on legacy version of Adonis you were able to extend Validator component. I've searching on internet even on the issues of the adonisjs/core project but I cant find a solution.

I've tried to add my rule directly with:

// AppProvider.ts
public async boot() {
    // IoC container is ready
    const validator = require('@ioc:Adonis/Core/Validator');
    validator.rules.uniqueMongo = () => false;
}

but clossest I get is seing this message message: "undefined" rule is not registered. Use "validator.rule" to add the rule."

Thank you! This is the most awesome framework I've seen for nodejs!

fershopls avatar Jul 26 '21 17:07 fershopls

Hi @fershopls

I have some custom rules, this is how i use:

1 - Create a file inside start folder, to define your custom rules. (ex: customRules.ts) 2 - For intelisense, create the file contracts/validator.ts to declare your custom rules types 3 - add ./start/customRules.ts at preloads object inside .adonisrc.json file. (this will make adonis read your file when start the application)

Examples:

start/customRules.ts

import { validator } from '@ioc:Adonis/Core/Validator';
import Env from '@ioc:Adonis/Core/Env';
import axios from 'axios';

validator.rule(
  'googleReCAPTCHA',
  async (value, _, { pointer, arrayExpressionPointer, errorReporter }) => {
    const secret = Env.get('GOOGLE_RECAPTCHA_SECRET');

    const response = await axios.post(
      'https://www.google.com/recaptcha/api/siteverify',
      `secret=${secret}&response=${value}`,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );

    if (!response.data.success) {
      errorReporter.report(
        pointer,
        'googleReCAPTCHA',
        undefined,
        arrayExpressionPointer
      );
    }
  },
  () => ({
    async: true,
  })
);

contracts/validator.ts

declare module '@ioc:Adonis/Core/Validator' {
  import { Rule } from '@ioc:Adonis/Core/Validator';

  export interface Rules {
    googleReCAPTCHA(): Rule;
  }
}

.adonisrc.json

"preloads": [
    "./start/routes",
    "./start/kernel",
    "./start/views",
    "./start/customRules"
  ],

I hope this works for you. 😄

rodrigorz avatar Jul 31 '21 13:07 rodrigorz

Thank you so much!!! Really cool

fershopls avatar Aug 01 '21 00:08 fershopls