Java 数字验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15646453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:24:24  来源:igfitidea点击:

Java Digits Validation

javaspringvalidationmodel-view-controller

提问by Renato Shumi

I'm using validation in a int attribute:

我在 int 属性中使用验证:

@Digits(integer=6,fraction=0)
private Integer idOrder;

But I wanted this attribute has exactly 6 digits.

但我希望这个属性正好有 6 位数字。

How can I do that? (Using JSP+Spring+Hibernate)

我怎样才能做到这一点?(使用JSP+Spring+Hibernate)

回答by digao_mb

As you need the 6 digits, I think you should use a String to the property. If in some situations you need it as int, you make a

由于您需要 6 位数字,我认为您应该对属性使用字符串。如果在某些情况下你需要它作为 int,你可以做一个

 public int getIdOrder(){ return Integer.parseInt(idOrder);}

On the String you can use pattern validation. It would be somethind like this:

在字符串上,您可以使用模式验证。它会是这样的:

@Pattern(regexp="\d{6}")
private String idOrder;

Another option, is keep the idOrder a int and make a getter for the string:

另一种选择是将 idOrder 保持为 int 并为字符串创建一个 getter:

public String getIdOrgetAsString(){
    String s = "000000" + idOrder;
    return s.substring(s.length() - 6);
}

Anyway, there are some options.

无论如何,有一些选择。

回答by Stefan Jansen

Are you sure your validation works at all?

你确定你的验证有效吗?

The Hibernate documentation says:

休眠文档说:

Check whether the property is a number having up to integer digits and fraction fractional digits. 1

检查该属性是否为最多具有整数位和小数位的数字。1

What means exactly 6 digits? Are leading zeros supported? Or should the number be between 100.000 and 999.999. In the first case, I guess your number should be a String (with @Length), and in the second case, I guess you should use @Min and @Max.

正好是 6 位数字是什么意思?是否支持前导零?或者数字应该在 100.000 和 999.999 之间。在第一种情况下,我猜您的数字应该是一个字符串(带有@Length),在第二种情况下,我猜您应该使用@Min 和@Max。