springboot表单验证

表单验证

1.前端效验

 data() {
 	//自定义效验方法
    var validateSort = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("排序不能为空"));
      } else if (!Number.isInteger(value) || value < 0) {
        callback(new Error("排序必须是一个大于0的整数"));
      } else {
        callback();
      }
    };
    
    return {
      visible: false,
      // 效验数据
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: 1,
        firstLetter: "",
        sort: "",
      },
      // 效验规则
      dataRule: {
        name: [{ required: true, message: "品牌名不能为空", trigger: "blur" }],
        logo: [
          { required: true, message: "品牌logo地址不能为空", trigger: "blur" },
        ],
        descript: [
          { required: true, message: "介绍不能为空", trigger: "blur" },
        ],
        showStatus: [
          {
            required: true,
            message: "显示状态[0-不显示;1-显示]不能为空",
            trigger: "blur",
          },
        ],
        firstLetter: [
          { required: true, message: "检索首字母不能为空", trigger: "blur" },
        ],
        sort: [
          {
          	//引用效验方法
            validator: validateSort,
            trigger: "blur",
          },
        ],
      },
    };
  },
  1. 后端效验
  • BrandEntity 实体类 注解 添加效验规则,并分组
/**
 * 品牌
 * 
 * @author wangyan
 * @email coolboywayan@gmail.com
 * @date 2021-09-03 22:54:52
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌Id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定品牌Id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotEmpty(message = "品牌名不能为空", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotEmpty(message = "logo地址不能为空", groups = {AddGroup.class})
	@URL(message = "logo地址不合法", groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(message = "检索字母不能为空", groups = {AddGroup.class})
	@Pattern(regexp = "/^[a-zA-Z]$/", message = "必须以字母开头", groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(message = "排序不能为空", groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于0", groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;
}

  • controller层 添加注解 启动效验
    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand){
		brandService.save(brand);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }
  • 集中处理所有的异常
/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.rock.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    /**
     * 效验异常处理
     *
     * @param validException
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException validException) {
        log.error("效验异常:{}", validException.getClass());
        log.error("异常信息:{}", validException.getMessage());
        BindingResult bindingResult = validException.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> map.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return R.error(StatusCode.VALID_EXCEPTION.getCode(), StatusCode.VALID_EXCEPTION.getMessage()).put("data", map);
    }

    /**
     * 处理任意类型的异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error();
    }

}
  • 自定义状态码
package com.rock.common.exception;

public enum StatusCode {
    UNKNOW_EXCEPTION(10000, "系统未知异常"),
    VALID_EXCEPTION(10001, "格式效验异常");

    private Integer code;
    private String message;

    StatusCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>