简体   繁体   中英

Validator not workind in Adonis

I'm setting some validations in my code, and I want to use Validator from Adonis framework. I followed all steps in official documentatio, but nothing worked.

I triend to follow official documentation. Installed Validator via CLI Create my validator class using adonis make:validator User Setted my rules Attached validator in my routes

Here is my route:

Route.resource('users', 'UserController')
  .apiOnly() 
  .middleware('auth')
  .validator(new Map(
    [['users.store'], ['User']
  ]
  ))

I expecte something like some messages, but just return knex erros.

edit: yes, I registered validator in my provides.

While using validators it is always good to create a validator class and write the rules and messages for those rules, then just attach that validator class to your routes. As adonis.js uses the Indicative library to do validation I would suggest you visit https://indicative.adonisjs.com/guides/master/introduction and check out how to write rules and messages.

create a validator folder in your app or src folder make sure you have adonis validator installed

create a login.js

class Login {
  get rules () {
    return {
        email: 'required|email',
        password: 'required'
    }
  }

  get messages () {
    return {
      'email.required': 'You must provide a email address.',
      'email.email': 'You must provide a valid email address.',
      'password.required': 'You must provide password.'
    }
  }

  async fails (errorMessages) {

    this.ctx.session.flash({ 
        alert: {
            message: errorMessages[0].message,
            type: 'warning'
        }
    });
    this.ctx.response.redirect('back');
    return
  }
}

then in the routes apply the validator like this

 Route.post('/login', 'AuthController.login').validator(['login'])

this technique also reduces the boiler plate code. And you can write validators and apply to multiple routes or route groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM