Custom Rule 'is not a function' in AdonisJS v5

Hi, I’ve been trying to add a new rule for the Validator in AdonisJS V5, the problem is although I’ve followed the guide, I still get an error message whenever I’m trying to add the newly added rule. Here’s the files that I created to add the new rule:

start/validationRules.ts

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

validator.rule('min', (value, _, {pointer, arrayExpressionPointer, errorReporter}) => {
  if (typeof (value) !== 'number') {
    return false
  }

  if (!Number.isInteger(value)) {
    errorReporter.report(pointer, 'min', 'Invalid value', arrayExpressionPointer)
  }
})

contracts/validator.ts

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

  export interface Rules {
    min(): Rule
  }
}

I’ve been trying to use it somewhere in one of my controller alike this:

  public async test({request}: HttpContextContract){
    return {
      data: await request.validate({
        schema: schema.create({
          test: schema.number([
            rules.min()
          ])
        })
      })
    }
  }

And I still got the following error:

{
  "message": "Validator_1.rules.min is not a function"
}

Is there something that I’m missing?

Thanks before!

1 Like

@virk helped me out with this one in AdonisJS’s Discord Server

The solution for it that I got from him is to replace the

{
  "file": "./start/validationRules",
  "environment": []
}

with

"./start/validationRules"

So, before @virk gave me the solution, my .adonisrc.json file look alike this:

{
  "typescript": true,
  "commands": [
    "./commands",
    "@adonisjs/core/build/commands",
    "@adonisjs/lucid/build/commands"
  ],
  "exceptionHandlerNamespace": "App/Exceptions/Handler",
  "aliases": {
    "App": "app",
    "Contracts": "contracts",
    "Config": "config",
    "Database": "database"
  },
  "preloads": [
    "./start/routes",
    "./start/kernel",
    {
      "file": "./start/validationRules",
      "environment": []
    }
  ],
  "providers": [
    "./providers/AppProvider",
    "@adonisjs/core",
    "@adonisjs/lucid"
  ],
  "metaFiles": [
    ".env",
    ".adonisrc.json"
  ]
}

The correct one should look somehow like this:

{
  "typescript": true,
  "commands": [
    "./commands",
    "@adonisjs/core/build/commands",
    "@adonisjs/lucid/build/commands"
  ],
  "exceptionHandlerNamespace": "App/Exceptions/Handler",
  "aliases": {
    "App": "app",
    "Contracts": "contracts",
    "Config": "config",
    "Database": "database"
  },
  "preloads": [
    "./start/routes",
    "./start/kernel",
    "./start/validationRules"
  ],
  "providers": [
    "./providers/AppProvider",
    "@adonisjs/core",
    "@adonisjs/lucid"
  ],
  "metaFiles": [
    ".env",
    ".adonisrc.json"
  ]
}

So the case is closed, big thanks to @virk for all the help.