IP
"(\d{1,3}\.){3}\d{1,3}"
身份证号
"^\d{15}$|^\d{17}[0-9Xx]$"
车牌号
"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂港澳]{1}$"
手机号
@Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\d{8})$", message = "手机号格式错误")
controller层传参,加上@Validated
注解
@PostMapping("save")
public RestResponse save(@Validated @RequestBody Video video) {
return this.wrap(videoService.save(video));
}
出错则抛出org.springframework.web.bind.MethodArgumentNotValidException
怎么返回给前端,详见
不是json则报org.springframework.validation.BindException
异常处理:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public RestResponse<Object> exceptionMethod1(MethodArgumentNotValidException e) {
RestResponse<Object> rr = new RestResponse<Object>();
BindingResult bindingResult = e.getBindingResult();
FieldError fieldError = bindingResult.getFieldError();
rr.setStatus("500");
rr.setMessage(fieldError.getField() + " " + fieldError.getDefaultMessage());
return rr;
}
@ExceptionHandler(BindException.class)
@ResponseBody
public RestResponse<Object> exceptionMethod2(BindException e) {
RestResponse<Object> rr = new RestResponse<Object>();
BindingResult bindingResult = e.getBindingResult();
FieldError fieldError = bindingResult.getFieldError();
rr.setStatus("500");
rr.setMessage(fieldError.getField() + " " + fieldError.getDefaultMessage());
return rr;
}
ip
/**
* ip正则验证
* @param ip
* @return false 不匹配
*/
public static boolean regexIp(String ip){
String regexIp = "^(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)$";
return (ip.matches(regexIp));
}