简体   繁体   English

Java 验证:验证对象中的对象

[英]Java Validation: Validate an object within an object

I have two objects:我有两个对象:

public class CancelRequest{
 @NotEmpty
 private String id;

 @NotNull
 private BookingDetails;
}

BookingDetails object:预订详情对象:

public class BookingDetails{
 @NotEmpty
 private String bookingId;
}

My class that is responsible for validating the request is CancelRequestValidator我负责验证请求的类是CancelRequestValidator

...
import javax.validation.Validator;
...
public class CancelRequestValidator{
...
public void check(CancelRequest request){
 Set<ConstraintViolation<NorthAmericaCancelTripRequest>> violations = 
validator.validate(request);
...
 }
}

how I am performing validation?我如何执行验证?

CancelRequest request = new CancelRequest("id",new BookingDetails(""));
CancelValidator validator = new CancelValidator();
violations = validator.check(request);

The violation should have one entry in it saying bookingId cannot be empty but instead it thinks that the object valid.违规中应该有一个条目,说明bookingId 不能为空,但它认为该对象有效。 I need to do the validation this way because I have some other business validation that I need to perform on this object hence I am using a mixture of javax and custom validation.我需要以这种方式进行验证,因为我需要对此对象执行一些其他业务验证,因此我混合使用了 javax 和自定义验证。

thanks谢谢

To perform nested bean validation, you need to use the @Valid annotation on the nested object:要执行嵌套 bean 验证,您需要在嵌套对象上使用@Valid批注:

public class CancelRequest{
  @NotEmpty
  private String id;

  @NotNull
  @Valid
  private BookingDetails;
}

As Eamon Scullion said, @Valid will work for nested validations, dont forget though to use @NotNull for Objects like Date, @NotBlank for text fields, and @NotEmpty for Iterable objects正如 Eamon Scullion 所说,@Valid 可用于嵌套验证,但不要忘记对 Date 等对象使用 @NotNull,对文本字段使用 @NotBlank,对 Iterable 对象使用 @NotEmpty

public class CancelRequest{
    @NotBlank
    private String id;
    

    @NotEmpty
    private List<E> myList;

    @NotNull
    @Valid
    private BookingDetails;
}

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

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