Can write validation rule for request parameter in adonis validator

My routes

/users/:userId

I am getting an error when writing like

get rules() {
  return {
    'userId' : 'required'
  }
}

Error

required validation failed on userId

Adonis version: 4.1
Validator version: 5.0

Note:- I am able to write validation rule for the request body.

1 Like

You can access that parameter through the context

Try this:

get rules () {
  const userId = this.ctx.params.userId
  return {
    userId: 'required'
  }
}

Sorry, Its not working

Please read docs carefully, your rules getter is returning nothing.
Try this :

get rules () {
  return {
    // your rules here...
  }
}

Yes, its my mistake, but this way working for request body not for request params.

Add this to validator class:

get data () {
  const requestBody = this.ctx.request.all()
  const userId = this.ctx.params.userId

 return Object.assign({}, requestBody, { userId })
}

Let me know if it works.

1 Like

Thanks @Melchyore,

Yes its working

1 Like

Hi @Melchyore

Thanks for your help. I did it and it now recognize the invalid regex, but now I’m having issues with the length.

This is are the rules:

      short_name:[
        rule('min',4),
        rule('max',20),
        rule('regex',/^[a-zA-Z0-9,. ]+$/)
      ],

sanitisation rule:
short_name:'escape'

If i send “Mi Super Empresa <<” which has 19 letters I’m getting the error ‘max validation failed on short_name’, error that I don’t have with 20 normal letters. If I take out the sanitization rule the validation runs ok.

As my regex is more restricted than ‘escape’ I’ll take out the sanitization rule, but the issue is there.

Again, thanks for your help!

B/R

@jorgeyoma That’s not an issue. If you read this carefully, you’ll understand why it fails : when you sanitize the input, the generated output will look like this
Mi Super Empresa &lt;&lt;
… with length above 20 when you escape it.

Hope it helps.

Hi @Melchyore
Thanks for the clarification.

B/R

1 Like