简体   繁体   中英

How to validate number using AdonisJS

I'm working on project using AdonisJS 4.1, I have a problem with validating number, here is my code in my code in the controller

const validation = await validate(request.all(), {
    posts_per_page: required|number|min:0
})

When I tried to fill the form field with any number larger than 0, it always give error message as following:

number validation failed on posts_per_page

Any help on resolving this issue will be much appreciated, thanks before.

The main issue here is that by default an HTML form will send all the fields as string. You need to sanitize them first using the sanitizer :

const { sanitize } = use('Validator')

const data = sanitize(request.all(), {
  posts_per_page: 'to_int',
})

Then you will be able to use data instead of request.all() for your validation.

Also, take notes that you should use request.only() instead of request.all() for security reasons.

The min rule evaluates the value length (ie the length of a string or an array), not the value itself. You need to user the above rule for this. Try

const validation = await validate(request.all(), {
    posts_per_page: 'required|number|above:0'
})
const rules = {
  posts_per_page: 'required|number|min:0'
}

const validation = await validate(request.all(), rules)

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