如何实现自己的 validation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

// 抛出异常
private void validateParam(Map<String, String> paramValues) {
boolean validate = MapUtils.isEmpty(paramValues)
|| !paramValues.containsKey(ParamConstant.CUSTOMER_N0)
|| StringUtils.isEmpty(paramValues.get(ParamConstant.CUSTOMER_N0));
if (validate) {
throw new DataBusinessException(ResultCodeEnum.PARAM_NULL);
}
}

// spring 的 valiator
public class ContactNumberValidator implements
ConstraintValidator<ContactNumberConstraint, String> {

@Override
public void initialize(ContactNumberConstraint contactNumber) {
}

@Override
public boolean isValid(String contactField,
ConstraintValidatorContext cxt) {
return contactField != null && contactField.matches("[0-9]+")
&& (contactField.length() > 8) && (contactField.length() < 14);
}

}

// valid 注解
@PostMapping("/addValidatePhone")
public String submitForm(@Valid ValidatedPhone validatedPhone,
BindingResult result, Model m) {
if(result.hasErrors()) {
return "phoneHome";
}
m.addAttribute("message", "Successfully saved phone: "
+ validatedPhone.toString());
return "phoneHome";
}