1. 前端校验
表单数据校验-elementUi 默认校验+自定义校验
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="活动区域" prop="region">
<el-select v-model="ruleForm.region" placeholder="请选择活动区域">
<el-option label="区域一" value="shanghai"></el-option>
<el-option label="区域二" value="beijing"></el-option>
</el-select>
<el-form-item label="首字母" prop="firstLetter">
<el-input v-model="ruleForm.firstLetter"></el-input>
</el-form-item>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
ruleForm: {
name: '',
region: '',
var validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('请选择活动区域!'));
} else {
callback();
}
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
region: [
{ validator: validatePass2, trigger: 'change' }
],
firstLetter: [
{ validator: (rule, value, callback) =>{
if(value == ''){
callback(new Error('首字母必须填写'));
}else if(!/^[a-zA-Z]&/.test(value)){
callback(new Error('首字母必须在a-z或者A-Z之间'));
}else{
callback();
}
}, trigger: 'blur'}
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
2. 后端校验
JSR303 给Bean 添加校验注解
@NotBlank(message = "姓名不能为空")
private String name;
开启校验 效果:校验错误后会有默认的响应
@PostMapping("/saveUser")
public Response saveUser(@Valid @RequestBody BaseUser baseUser) {
}
获取校验错误信息
@PostMapping("/saveUser")
public Response saveUser(@Valid @RequestBody BaseUser baseUser, BindingResult result) {
if (result.hasErrors()) {
Map<String, String> map = new HashMap<>();
result.getFieldErrors().forEach(item -> {
String field = item.getField();
String message = item.getDefaultMessage();
map.put(field, message);
});
return new Response().error().data(map);
} else {
return new Response().success();
}
}
自定义校验规则
@NotEmpty
@URL(message = "必须填写正确的url地址")
private String url;
@Pattern(regexp = "/^[a-zA-Z]$/", message = "首字母必须是一个字母")
private String firstLetter;
@Min(value = 0, message = "排序必须大于等于0")
private Integer sort;
定义统一异常类处理
将方法改为正常方法
@PostMapping("/saveUser")
public Response saveUser(@Valid @RequestBody BaseUser baseUser) {
BaseUser baseUsers = baseUserService.findByName(baseUser.getName());
if (baseUsers != null) {
return new Response().error().data("姓名已存在");
}
baseUserService.saveUser(baseUser.getName(), baseUser.getPassword());
return new Response().success();
}
在exception包下,创建处理统一异常类
@Slf4j
@RestControllerAdvice(basePackages = "com.mrfei.fun.controller")
public class AllExceptionControllerAdvice {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Response handlerValidException(MethodArgumentNotValidException e) {
log.error("数据校验出现问题:{},异常类型:{}", e.getMessage(), e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String, String> map = new HashMap<>();
bindingResult.getFieldErrors().forEach(item -> {
String field = item.getField();
String message = item.getDefaultMessage();
map.put(field, message);
});
return new Response().error().data(map);
}
}
分组校验 首先在valid包下创建好分组类 只会对标注了分组的字段进行校验,没有标注分组的字段不会进行校验
@NotBlank(message = "姓名不能为空", groups = {AddGroup.class, UpdateGroup.class})
private String name;
@PostMapping("/saveUser")
public Response saveUser(@Validated(AddGroup.class) @RequestBody BaseUser baseUser) {
}
自定义校验 在valid包下编写一个自定义的校验注解
@Documented
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValue {
String message() default "{com.mrfei.fun.valid.ListValue.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int[] vals() default {};
}
创建自定义校验类ListValueConstraintValidator
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
private Set<Integer> set = new HashSet<>();
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
for (int val : vals) {
set.add(val);
}
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
if (set.contains(value)) {
return true;
} else {
return false;
}
}
}
在resources下创建ValidationMessages.properties 配置默认自定义注解中message的信息
com.mrfei.fun.valid.ListValue.message=必须提交指定的值
|