简体   繁体   English

Java Bean验证号码格式问题

[英]Java Bean Validation number formatting issue

I am struggling with Bean Validation to validate a Double attribute. 我正在努力与Bean验证来验证Double属性。

My application uses AngularJS with Java EE (JAX-RS / JAXB) for the backend. 我的应用程序将AngularJS与Java EE(JAX-RS / JAXB)一起用于后端。

My class looks like: 我的课看起来像:

public class MyClass {

  @NotNull
  Double value;

  // empty constructor, getters, setters

}

If I either send to the server, the JSON representation of MyClass as : 如果我发送到服务器,则MyClass的JSON表示为:

{ value: '' }

Or 要么

{ value: '456q' }

I end up with a validation constraint violation for value "must not be null". 我最终遇到了验证约束违规,其值“一定不能为null”。

I would have liked a validation constraint for type formatting issue for the second JSON representation. 我希望第二个JSON表示形式的类型格式化问题有一个验证约束。

Is there any way to do it beside client side validation? 除了客户端验证之外,还有其他方法吗?

The value that you are sending are of string type. 您发送的值是字符串类型。 Try sending 尝试发送

{ value: 456 }

Now it's a number and validation should work fine. 现在是一个数字,验证应该可以正常进行。

That's because your JSON is sent as string, then casted as Double (using something like Double.valueOf("456q") ), and javax.validation does not have the knowledge of that string. 那是因为您的JSON是作为字符串发送的,然后被Double.valueOf("456q")为Double(使用Double.valueOf("456q") ),而javax.validation不了解该字符串。

However, it is still checked as a number (null is returned in invalid case). 但是,仍将其检查为数字(在无效情况下返回null)。

If you really want to do a format check, then you should probably store the value as a String, and cast it as a Double when needed. 如果您确实要进行格式检查,则可能应将值存储为字符串,并在需要时将其强制转换为Double。

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

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