开发中常常会有一些表单提交的字段限制,比如手机号,邮箱等等。这里简单写一下怎么实现校验方法吧
引入依赖
这里用的是springboot的项目,直接导入spring-boot-starter-web这个依赖就行了,他会自带hibernate-validator的依赖。

添加验证注解
在vo类或bo类属性上添加相关的验证注解,常用的有非空,email验证,最长最小长度验证等。

示例
public class UserVO {
private String username;
private String password;
private String confirmPassword;
@NotBlank(message = "用户昵称不能为空")
@Length(max = 12, message = "用户昵称不能超过12位")
private String nickname;
@Length(max = 12, message = "用户真实姓名不能超过12位")
private String realname;
@Pattern(regexp = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$", message = "手机号格式不正确")
private String mobile;
@Email
private String email;
@Min(value = 0, message = "性别选择不正确")
@Max(value = 2, message = "性别选择不正确")
private Integer sex;
private Date birthday;
}
获取校验错误信息
接下来就是controller请求时获取验证错误信息,主要就是@Valid注解和BindingResult获取错误信息,这里通过map封装了获取错误信息的方法
public void update(
@RequestParam String userId,
@RequestBody @Valid UserVO userVO,
BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
//判断BindingResult是否保存错误的验证信息,如果有,则直接return
if (result.hasErrors()) {
Map<String, String> errorMap = getErrors(result);
return Result.errorMap(errorMap);
}
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<>();
//获取错误校验的字段
List<FieldError> errorList = result.getFieldErrors();
for (FieldError error : errorList) {
//发生验证错误所对应的某个属性
String errorField = error.getField();
//验证错误的信息
String errorMsg = error.getDefaultMessage();
map.put(errorField, errorMsg);
}
return map;
}
over....
等等,如果我想自定义校验规则咋整呢?
自定义校验规则
想自定义校验规则,那我们先看看自带的校验注解咋写的。


发现基本上都会带着这三个属性,@Constraint主要是校验规则的实现,需要继承ConstraintValidator,照着写下。
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyValidConstraint {
String message();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
下面写具体的校验规则器,需要的方法如下

public class MyConstraintValidator implements ConstraintValidator<MyValidConstraint,Object> {
@Autowired
private HelloService helloService;
/**
* 校验器初始化
* @param constraintAnnotation
*/
@Override
public void initialize(MyValidConstraint constraintAnnotation) {
System.out.println("MyConstraintValidator--init ");
}
/**
* 真正的校验方法
* @param value
* @param context
* @return
*/
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
helloService.greeting("tom");
System.out.println(value);
return false;
}
}
ok,差不多就这样吧...