简体   繁体   中英

How i can make custom validators in adonis /node.js?

Actually i have one function store(){} in my controller that make several validations, this validations return response status specific, i'm thinking if exist one way that i can import this validations and test before the create() method.

Actually my code is:

async store ({ request, response }) {

    const qt_options_menor_0 = this.verificaOptionsMenor0(request.body.qt_options)
    if(qt_options_menor_0){
      return response
      .status(406)
      .json({ message: "Não é possível cadastrar quantidade de opções menor que 0" });
    }

    const qt_options_igual_0 = this.verificaOptionsIgual0(request.body.qt_options)
    if(qt_options_igual_0)
      return response
      .status(406)
      .json({ message: "Não é possível cadastrar quantidade de opções igual a 0" });

 const parameter = {
      ...request.all(),
      user_id: request.user_id
    }
    const parametroCriado = await Parameter.create(parameter)
    return parametroCriado
  }

       verificaQtQuizSendIgual0(qt_quiz_send){
    if(qt_quiz_send === 0){
      return true
    }else{
      return false
    }
  }

  verificaOptionsMenor0(qt_options){
    if(qt_options < 0){
      return true
    }else{
      return false
    }
  }

This way my controller have much code, there's a better way to do this?

You can use Adonis validator

Like:

Validator file

'use strict'

class Option {
  get rules() {
    return {
      // Your rules
    }
  }

  get messages() {
    var antl = this.ctx.antl;
    return {
       // Custom messages
    }
  }

  async fails(errorMessages) {
    return this.ctx.response.status(406).json({ message: "Não é possível cadastrar quantidade de opções menor que 0" });
  }
}

module.exports = Option

Command

> adonis make:validator Option

Use validator - start/route.js

...
Route
  ...
  .validator('Option')

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