简体   繁体   English

如何使用 AdonisJS 验证数字

[英]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我正在使用 AdonisJS 4.1 处理项目,我在验证数字时遇到问题,这是我在控制器代码中的代码

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:当我尝试用大于 0 的任何数字填充表单字段时,它总是给出如下错误消息:

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.这里的主要问题是默认情况下,HTML 表单会将所有字段作为字符串发送。 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.然后您将能够使用data而不是request.all()进行验证。

Also, take notes that you should use request.only() instead of request.all() for security reasons.另外,请注意出于安全原因,您应该使用request.only()而不是request.all()

The min rule evaluates the value length (ie the length of a string or an array), not the value itself. min规则评估值的长度(即字符串或数组的长度),而不是值本身。 You need to user the above rule for this.为此,您需要使用above规则。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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