Java 如何在注释的帮助下限制用户在整数字段中输入数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18853347/
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
How to restrict a user to enter numerics in a Integer field with help of annotations?
提问by Narendra Pandey
I need to restrain a user to enter numeric values in a jsp field.On failure it should give relevant message.This is my current declaration:
我需要限制用户在 jsp 字段中输入数值。失败时,它应该给出相关消息。这是我当前的声明:
@NotNull
@Column(value="userId")
private Long userId;
I need to know what more annotations do i need to add, to get my desired result without changing data type of the field.
我需要知道我还需要添加哪些注释,才能在不更改字段数据类型的情况下获得所需的结果。
回答by Sotirios Delimanolis
This isn't something that would be done on the validation level.
这不是在验证级别上完成的事情。
When you enter something in a form and you submit that form, the browser will send an HTTP request with your <input>
fields serialized and sent as request parameters. Spring then, based on the data type of your bean's field, tries to convert from a String
request parameter value to a Long
type. If it can't do that because the String is not a Long
, it will throw exceptions (NumberFormatException
) and respond with a 400 error code.
当您在表单中输入内容并提交该表单时,浏览器将发送一个 HTTP 请求,其中您的<input>
字段被序列化并作为请求参数发送。然后,Spring 根据 bean 字段的数据类型尝试从String
请求参数值转换为Long
类型。如果因为 String 不是 a 而不能这样做,Long
它将抛出异常 ( NumberFormatException
) 并以 400 错误代码响应。
You can validate this on the (HTML5) client side with
您可以在(HTML5)客户端验证这一点
<input name="userId" type="number">
Or use
或使用
<input type="text" pattern="\d*" />
if you don't want decimal numbers.
如果你不想要十进制数字。
回答by Prabhakaran Ramaswamy
Hibernate
休眠
@Range - Check if the value is between min and max
@Range - 检查值是否在最小值和最大值之间
Example
例子
@Range(min=1, max=1000)
@Pattern - Check if the property match the regular expression given a match flag @Pattern(regex="regexp", flag=) or @Patterns( {@Pattern(...)} )
@Pattern - 检查属性是否与给定匹配标志的正则表达式匹配 @Pattern(regex="regexp", flag=) 或 @Patterns( {@Pattern(...)} )
Example
例子
@Pattern(regex = "[0-9]+")
Spring
春天
@RegExp - Check if the property match the regular expression given a match flag
@RegExp - 检查属性是否与给定匹配标志的正则表达式匹配
Example
例子
@RegExp("[0-9]+")