赞
踩
//定义校验规则 rules: { name: [ {required: true, message: "请输入家居名", trigger: "blur"} ], maker: [ {required: true, message: "请输入制造商名", trigger: "blur"} ], price: [ {required: true, message: "请输入价格", trigger: "blur"}, {pattern: /^([1-9])\d*|0(\.\d+)?$/, message: "请输入数字", trigger: "blur"} ], sales: [ {required: true, message: "请输入销量", trigger: "blur"}, {pattern: /^([1-9])\d*|0(\.\d+)?$/, message: "请输入数字", trigger: "blur"} ], stock: [ {required: true, message: "请输入库存", trigger: "blur"}, {pattern: /^([1-9])\d*|0(\.\d+)?$/, message: "请输入数字", trigger: "blur"} ] }
//判断表单校验是否通过 this.$refs['form'].validate(valid => { //如果校验不通过则弹出提示框 if (!valid) { this.$message( { type: "error", message: "校验失败!" } ) return false; //放弃提交表单 } else { //如果form没有id则说明这个提示框是新增的提示框 //发送post请求并携带form这个js对象的数据,会以json格式进行发送 request.post("/api/save", this.form).then( res => { console.log("res=", res); this.dialogVisible = false; //调用list方法,刷新家居信息 this.list(); } ) } })
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
@NotEmpty(message = "请输入家居名") private String name; @NotEmpty(message = "请输入制造厂商") private String maker; @NotNull(message = "请输入数字") @Range(min = 0, message = "价格不能小于0") private BigDecimal price; @NotNull(message = "请输入数字") @Range(min = 0, message = "销量不能小于0") private Integer sales; @NotNull(message = "请输入数字") @Range(min = 0, message = "库存不能小于0") private Integer stock;
@ResponseBody //将结果转换成json字符串返回 @PostMapping("/save") public Msg save(@Validated @RequestBody Furn furn, Errors errors) { //将接受到的json字符串转换成Furn对象 //用来存储错误信息的map Map<String, Object> errorMap = new HashMap<>(); //获取所有的error List<FieldError> fieldErrors = errors.getFieldErrors(); //遍历错误并放到map中 for (FieldError fieldError : fieldErrors) { errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()); } //判断map是否为空,为空则表示没有错误 if (errorMap.isEmpty()) { furnService.save(furn); return Msg.success(); //如果没有报错,则返回成功的Msg对象 } else { //将信息放错误的Msg中并返回 return Msg.fail().add("errMsg", errorMap); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。