java 如何使用 spring 注释检查字符串是否为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25518224/
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-11-02 08:09:54  来源:igfitidea点击:

how check string is integer or not by using spring annotations?

javaspringspring-mvc

提问by Suraj

**i want test user input is a alpha-numeric or integer by using spring form annotations **

**我希望通过使用弹簧形式注释测试用户输入是字母数字或整数**

i have also tried this code.
i have also tried this code.
 @NotEmpty
        @NumberFormat(style = Style.NUMBER)
        @Length(min =11,max =11)
        @Column(name="abc")
        private String xyz;

采纳答案by adchilds

The @NumberFormatannotationonly applies to subclasses of java.lang.Number (Integer, Float, Double, BigDecimal, etc.); therefore, it won't work with Strings. For this, you may have to create a custom annotation that validates the String only contains numbers.

@NumberFormat注释仅适用于java.lang.Number中(的子类整数浮点BigDecimal的,等); 因此,它不适用于字符串。为此,您可能需要创建一个自定义注释来验证字符串仅包含数字。

Take a look at the following tutorial; it's very thorough on how to create custom annotations and use them for validation with Spring: http://softwarecave.org/2014/03/27/custom-bean-validation-constraints/

看看下面的教程;关于如何创建自定义注释并将它们用于 Spring 验证非常详尽:http: //softwarecave.org/2014/03/27/custom-bean-validation-constraints/

回答by randal4

I ran into a similar problem and used the @Patternannotation to compare against a regular expression.

我遇到了类似的问题,并使用@Pattern注释与正则表达式进行比较。

@Pattern(regexp="^(0|[1-9][0-9]*)$")

The annotation is part of the javax.validation.constraintspackage.

注释是javax.validation.constraints包的一部分。