一、数据库验证
//service/studentService
const Student = require("../models/Student");
const { Op } = require("sequelize");
const Class = require("../models/Class");
const validate = require("validate.js");
var dayjs = require('dayjs');
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
const { pick } = require("../util/propertyHelper");;
exports.addStudent = async function (stuObj) {
stuObj = pick(stuObj, "name", "birthday", "sex", "mobile", "ClassId");//将需要的属性筛选,避免用户恶意传入值
validate.validators.classExits = async function (value) {//班级是否存在去数据库验证,所以是异步
const c = await Class.findByPk(value);
if (c) {
return;
}
return "is not exist";
};
const rule = {//验证规则
name: {
presence: {
allowEmpty: false,
},
type: "string",
length: {
minimum: 1,
maximum: 10,
}
},
birthday: {
presence: {
allowEmpty: false,
},
datetime: {
dateOnly: true,//将日期转换成时间戳
earliest: +dayjs.utc().subtract(70, "y"),//最大不能超过70岁
latest: +dayjs.utc().subtract(10, "y"),//最小不能低于10岁
}
},
sex: {
presence: true,
type: "boolean",
},
mobile: {
presence: {
allowEmpty: false,
},
format: /1\d{10}/,
},
ClassId: {//班级是否存在的验证需要自行封装
presence: true,
numericality: {
onlyInteger: true,
strict: false,
},
classExits: true,//封装的班级存在验证规则
}
}
await validate.async(stuObj, rule);//因为有班级的异步验证,这里也需要异步
//验证通过则添加,失败则报错停止添加
const ins = await Student.create(stuObj);
return ins.toJSON();
};
///util/propertyHelper
exports.pick = function (obj, ...props) {
if (!obj || typeof obj !== "object") {//不是对象
return obj;
}
const newObj = {};
for (const key in obj) {//是对象,赛选数据库需要的属性
if (props.includes(key)) {
newObj[key] = obj[key];
}
}
return newObj;
};
//services/studentService
const validate = require("validate.js");
var dayjs = require('dayjs');
var utc = require('dayjs/plugin/utc')
dayjs.extend(utc)
validate.extend(validate.validators.datetime,{//生日验证规则
/**
* 该函数会自动用于日期格式转换
* 它会在验证时自动触发,它需要将任何数据转换为时间戳返回
* 如果无法转换,返回NaN
* @param {*} value 传入要转换的值
* @param {*} options 针对某个属性的验证配置
*/
parse(value,options){
let formats = ["YYYY-MM-DD HH:mm:ss", "YYYY-M-D H:m:s", "x"];//允许的日期格式
if (options.dateOnly) {
formats = ["YYYY-MM-DD", "YYYY-M-D", "x"];
}
return +dayjs.utc(value, formats, true);
},
/**
* 用户显示错误消息时,使用的显示字符串
*/
format(value, options) {
let format = "YYYY-MM-DD";
if (!options.dateOnly) {
format += " HH:mm:ss";
}
return dayjs.utc(value).format(format);
},
})
//index
const stuSer = require("./services/studentService");
require("./init");
stuSer.addStudent({
name: "小雷",
birthday: '2008-5-17',
sex: true,
mobile: '17671234628',
ClassId: '13',
deletedAt: "2010-1-1",
a: 3,
b: 4,
}).catch((res)=>{
console.log(res);
});
时间不符合需求
添加成功
已经剔除了不需要的属性
博主开始运营自己的公众号啦,感兴趣的可以关注“飞羽逐星”微信公众号哦,拿起手机就能阅读感兴趣的文章啦!