二十六.新增修改品牌服务加上数据校验,保证数据的正确性

一.前端加上表单校验

修改brand-add-or-update.vue文件,加上表单校验规则:

<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="140px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="logo">
        <!-- <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input> -->
        <single-upload v-model="dataForm.logo"></single-upload>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <el-switch
          v-model="dataForm.showStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input v-model="dataForm.firstLetter" placeholder="检索首字母"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import SingleUpload from "@/components/upload/singleUpload";
export default {
  components: { SingleUpload },
  data() {
    return {
      visible: false,
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: 1,
        firstLetter: "",
        sort: 0
      },
      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: [
          {
            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"
          }
        ],
        sort: [
          {
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error("排序字段必须填写"));
              } else if (!Number.isInteger(value) || value < 0) {
                callback(new Error("排序必须是一个大于等于0的整数"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    init(id) {
      this.dataForm.brandId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.brandId) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/info/${this.dataForm.brandId}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name;
              this.dataForm.logo = data.brand.logo;
              this.dataForm.descript = data.brand.descript;
              this.dataForm.showStatus = data.brand.showStatus;
              this.dataForm.firstLetter = data.brand.firstLetter;
              this.dataForm.sort = data.brand.sort;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/${!this.dataForm.brandId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              brandId: this.dataForm.brandId || undefined,
              name: this.dataForm.name,
              logo: this.dataForm.logo,
              descript: this.dataForm.descript,
              showStatus: this.dataForm.showStatus,
              firstLetter: this.dataForm.firstLetter,
              sort: this.dataForm.sort
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>

效果如下:
二十六.新增修改品牌服务加上数据校验,保证数据的正确性_第1张图片

二.后端加上相应的校验规则

使用JSR303数据校验,给需要校验的实体加上相应注解规则:

package com.jiejie.webshop.prodect.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;

import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;

/**
 * 品牌
 *
 * @author ${author}
 * @email [email protected]
 * @date 2020-06-02 23:44:05
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
    /**
     * 添加组
     */
    public interface add {
    }

    /**
     * 更新组
     */
    public interface update {
    }

    private static final long serialVersionUID = 1L;

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

}

以上注解中有个分组的概念,这是为了区分新增和修改的一些不同规则,比如新增要求品牌id必须为空,而修改则要求品牌id必须不为空,所以加上分组来做区分。

修改BrandController类,对新增和修改的请求体加上**@Validate**注解,表示该请求体需要验证,同时使用BindingResult类型参数,对错误信息做一个整合,返回相关提示:

package com.jiejie.webshop.prodect.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jiejie.webshop.prodect.entity.BrandEntity;
import com.jiejie.webshop.prodect.service.BrandService;
import com.jiejie.common.utils.PageUtils;
import com.jiejie.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author ${author}
 * @email [email protected]
 * @date 2020-06-02 23:44:05
 */
@RestController
@RequestMapping("prodect/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 保存
     */
    @PostMapping("/save")
    //@RequiresPermissions("prodect:brand:save")
    public R save(@Validated(BrandEntity.add.class) @RequestBody BrandEntity brand, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            HashMap error = new HashMap<String, String>();
            bindingResult.getFieldErrors().forEach((item) -> {
                //获取到错误的属性名以及错误的消息
                error.put(item.getField(), item.getDefaultMessage());
            });
            return R.error(400, "提交的数据不合法").put("data", error);
        } else {
            brandService.save(brand);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    //@RequiresPermissions("prodect:brand:update")
    public R update(@Validated(BrandEntity.update.class) @RequestBody BrandEntity brand, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            HashMap error = new HashMap<String, String>();
            bindingResult.getFieldErrors().forEach((item) -> {
                //获取到错误的属性名以及错误的消息
                error.put(item.getField(), item.getDefaultMessage());
            });
            return R.error(400, "提交的数据不合法").put("data", error);
        } else {
            brandService.updateById(brand);
        }
        return R.ok();
    }
}

三.测试后端校验规则是否生效

以下是新增接口的请求信息:

POST http://localhost:88/api/prodect/brand/save
Accept: application/json
Cache-Control: no-cache
Content-Type: application/json

{
  "brandId": "1",
  "name": "",
  "logo": "",
  "descript": "",
  "showStatus": "",
  "firstLetter": "",
  "sort": ""
}

调用新增接口,返回结果如下:
二十六.新增修改品牌服务加上数据校验,保证数据的正确性_第2张图片
以下是修改接口的请求信息:

POST http://localhost:88/api/prodect/brand/update
Accept: application/json
Cache-Control: no-cache
Content-Type: application/json

{
  "name": "",
  "logo": "",
  "descript": "",
  "showStatus": "",
  "firstLetter": "",
  "sort": ""
}

调用修改接口,返回结果如下:
二十六.新增修改品牌服务加上数据校验,保证数据的正确性_第3张图片
可以看到新增和修改已经有了相关的校验提示了。

这样通过前端以及后端的校验规则,就能够更大的保证数据正确性了。

你可能感兴趣的:(从零开始搭建一个电商系统)