REF-spring REF-etc Validataion-Group
spring 에는 annotation으로 form 필드를 자동으로 체크할 수가 있다.
일반적으로는
xxForm.java 파일을 하나 만들고 그 안에 Form과 일치하도록 모든 Field를 정의한 다음에...
각 필드별로 여러가지 constraint를 정의할 수 있다.
@Pattern : Regex패턴 체크.
@NotNull @Null
@Size(min=2, max=30)
@Past (지난 날짜) @Future
@Max @Min @DecimalMax @DecimalMin 2Digits
@AssertFalse @AssertTrue
<기본사용>
예제)
public class MyForm {
@NotNull(message = "{error.not_input}")
@Length(max = 3, message = "{error.max_length}")
private String age;
@NotNull(message = "{error.not_input}")
@Length(max = 255, message = "{error.max_length}")
private String name;
@Pattern(regexp = MyConstant.MAIL_ADDRESS, message = "{error.mail_address_format_error}")
private String email;
}
컨트롤러에서 아래와 같은 형태로 값을 받는다.
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult)
==========1=====================
간단히 Override로 Custom Validator를 만들 수 있다.
@Data
@NoArgsConstructor
@CmsMemberMailValidator(newMailAddressField = "newMailAddress", mailConfirmField = "mailConfirm")
public class CmsMemberMailModifyForm {
private Long id;
private String displayName;
private String status;
private String organizationName;
private String mailAddress;
@NotNull(message = "{error.mail_address_null_error}")
@Pattern(regexp = WebConstantShared.MAIL_ADDRESS, message = "{error.mail_address_format_error}")
private String newMailAddress;
@NotNull(message = "{error.mail_address_null_error}")
private String mailConfirm;
public static CmsMemberMailModifyForm of(CmsMemberDetail cmsMemberDetail) {
CmsMemberMailModifyForm form = new CmsMemberMailModifyForm();
BeanUtils.copyProperties(cmsMemberDetail, form);
return form;
}
}
|
| @Target({ TYPE })
@Documented
|
| @Retention(RUNTIME) |
| @Constraint(validatedBy = Validator.class) |
| public @interface CmsMemberMailValidator { |
|
|
| String message() default "{error.mail_address_format_error}"; |
| |
| Class<?>[] groups() default {}; |
| |
| Class<? extends Payload>[] payload() default {}; |
| |
| String newMailAddressField(); |
| |
| String mailConfirmField(); |
| |
| class Validator implements ConstraintValidator<CmsMemberMailValidator, Object> { |
| |
| private String message; |
| |
| private String newMailAddressField; |
| |
| private String mailConfirmField; |
| |
| @Override |
| public void initialize(CmsMemberMailValidator constraintAnnotation) { |
| message = constraintAnnotation.message(); |
| newMailAddressField = constraintAnnotation.newMailAddressField(); |
| mailConfirmField = constraintAnnotation.mailConfirmField(); |
| } |
| |
| @Override |
| public boolean isValid(Object value, ConstraintValidatorContext context) { |
| BeanWrapper beanWrapper = new BeanWrapperImpl(value); |
| String newMailAddressValue = (String) beanWrapper.getPropertyValue(newMailAddressField); |
| String mailConfirmValue = (String) beanWrapper.getPropertyValue(mailConfirmField); |
| |
| //check only different case (null & blank Error_Message is processed on @NotNull annotation) |
| if (newMailAddressValue != null && StringUtils.isNotBlank(newMailAddressValue) |
| && mailConfirmValue != null && StringUtils.isNotBlank(mailConfirmValue) && !mailConfirmValue |
| .equals(newMailAddressValue)) { |
| |
| context.disableDefaultConstraintViolation(); |
| context.buildConstraintViolationWithTemplate(message) |
| .addPropertyNode(mailConfirmField) |
| .addConstraintViolation(); |
| return false; |
| } |
| |
| return true; |
| } |
| } |
| } |
==========2===================
위보단 약간 복잡하지만 좀 더 많은 기능이 있는 @InitBinder를 이용해
Custom Validator를 만들 수 있다.
Custom Validator: spring-REF Ref-InitBinder
Custom Validation Class를 만들 수도 있다.
.
< Valid vs Validated > REF1simple, REF2,
Validated는 spring 소속이고, Valid는 java소속인데
Validated가 Validataion-Group을 지정할 수 있다.
에러메시지도 출력가능하다. REF