const nameRule = {name: { type: 'string', required: true,format:/^[\u4e00-\u9fa5]{2,10}$/,message:"书名格式错误"}} // 记得改 const publishRule = {name: { type: 'string', required: true,format:/^[\u4e00-\u9fa5]{2,10}$/,message:"书名格式错误"}} const authorRule = {author:
时间: 2024-02-25 11:55:28 浏览: 174
npm-namecard:npm 名片库
把这三个定义规则的对象合并成一个对象,可以使用 ES6 的对象扩展运算符(...),将多个对象合并成一个新的对象。
例如,可以将这三个对象合并成一个对象,代码如下:
```
const commonRule = {
name: {
type: 'string',
required: true,
format: /^[\u4e00-\u9fa5]{2,10}$/,
message: "格式错误"
},
publish: {
type: 'string',
required: true,
format: /^[\u4e00-\u9fa5]{2,10}$/,
message: "格式错误"
},
author: {
type: 'string',
required: true,
format: /^[\u4e00-\u9fa5]{2,10}$/,
message: "格式错误"
}
};
```
然后,可以定义其他对象,使用对象扩展运算符(...)将 commonRule 对象合并进去,代码如下:
```
const nameRule = {...commonRule, name: {...commonRule.name, message: "书名格式错误"}};
const publishRule = {...commonRule, publish: {...commonRule.publish, message: "出版社格式错误"}};
const authorRule = {...commonRule, author: {...commonRule.author, message: "作者姓名格式错误"}};
const priceRule = {price: {...commonRule.price, type: "number", min: 0, max: 1000, message: "书本定价出错"}};
const quantityRule = {quantity: {...commonRule.quantity, type: "number", min: 0, message: "书本数量出错"}};
```
这样,就可以将公共的规则抽离出来,避免了代码的重复编写,提高了代码的可读性和可维护性。
阅读全文