我在 AdonisJs 中的自定义验证器不工作

My custom validator in AdonisJs is not working

我遵循了关于如何制作自定义验证器的 Adonis 文档。我把它做得这么简单只是为了测试。

当我制作 "post" 时,我收到消息 "cpf is not defined as a validation rule"

代码:

Cpf.js

const Validator = use('Validator')

const cpfValidation = async (data, field, message, args, get) => {
  const value = get(data, field)

  console.log('This line is on console!')

  if (!row) {
    throw message
  }
}

Validator.extend('cpf', cpfValidation)

User.js

'use strict'

class User {

  get validateAll() {
    return true
  }

  get rules() {
    return {
      name: 'required',
      lastname: 'required',
      email: 'required|email|unique:users',
      cpf: 'cpf',
      birthday: 'required',
      password: 'required|min:6|max:20'
    }
  }
}

module.exports = User

结果: https://i.imgur.com/J5L8Y0O.png

有什么想法吗?

经过一番折腾,我找到了解决办法。

首先,我必须安装 adonis 提供程序验证: adonis 安装@adonisjs/validator

并将其放在start/app.js:

里面的提供者列表中
const providers = [
  '@adonisjs/validator/providers/ValidatorProvider'
]

然后我通过以下方式创建一个新的提供者: adonis make:provider 自定义提供程序

它将在根文件夹 "providers" 上创建一个新的提供程序。

我的 class 代码是:

'use strict'

const { ServiceProvider } = require('@adonisjs/fold')

class CustomValidator extends ServiceProvider {

  async isCpfCorrect(data, field, message, args, get) {
    const cpf = get(data, field);

    //It will be validated by "unique" validation, if value is null
    if(!cpf){
       return
    }

    /*
      ALL MY LOGIC SHOULD BE HERE...
    */

  }

  register() { }

  boot() {
    const Validator = use('Validator');
    Validator.extend('cpf', this.isCpfCorrect);
  }
}

module.exports = CustomValidator

然后我必须在 start/app.js:

的提供者列表中添加这个提供者
const path = require('path')

const providers = [
  '@adonisjs/framework/providers/AppProvider',
  '@adonisjs/auth/providers/AuthProvider',
  '@adonisjs/bodyparser/providers/BodyParserProvider',
  '@adonisjs/cors/providers/CorsProvider',
  '@adonisjs/lucid/providers/LucidProvider',
  '@adonisjs/mail/providers/MailProvider',
  '@adonisjs/framework/providers/ViewProvider',
  '@adonisjs/validator/providers/ValidatorProvider',
  path.join(__dirname, '..', 'providers', 'CustomValidator')
]

然后我将能够在验证中使用我的提供商:

'use strict'

class User {

  get validateAll() {
    return true
  }

  get rules() {
    return {
      name: 'required',
      lastname: 'required',
      email: 'required|email|unique:users',
      cpf: 'required|cpf' <--------------- here is my custom provider for cpf,
      birthday: 'required',
      password: 'required|min:6|max:20'
    }
  }
}

module.exports = User

我在文档中找到的所有这些:

https://adonisjs.com/docs/4.1/service-providershttps://adonisjs.com/docs/4.1/extending-adonisjs

干杯。