技术实践

sequelize模型验证规则

在众多的MVC框架当中,基本上都会带有模型验证工能,当然Egg.js也不除外

羊先生的头像
羊先生2022.01.02 · 1 分钟阅读 · 55 阅读
sequelize模型验证规则封面
文章正文还需 1 分钟

模型验证

在众多的MVC框架当中,基本上都会带有模型验证工能,当然Egg.js也不除外

安装

bash 复制代码
npm install --save sequelize

安装数据库

js 复制代码
# 选择以下之一:
npm install --save pg pg-hstore # Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious # Microsoft SQL Server

链接数据库

js 复制代码
const { Sequelize } = require('sequelize');

// 方法 1: 传递一个连接 URI
const sequelize = new Sequelize('sqlite::memory:') // Sqlite 示例
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Postgres 示例

// 方法 2: 分别传递参数 (sqlite)
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: 'path/to/database.sqlite'
});

// 方法 3: 分别传递参数 (其它数据库)
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: /* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */
});
js 复制代码
var ValidateMe = sequelize.define('foo', {
  foo: {
    type: Sequelize.STRING,
    validate: {
      is: ["^[a-z]+$",'i'],     // 只允许字母
      is: /^[a-z]+$/i,          // 只允许字母
      not: ["[a-z]",'i'],       // 不能使用字母
      isEmail: true,            // 检测邮箱格式 (foo@bar.com)
      isUrl: true,              // 检查Url格式 (http://foo.com)
      isIP: true,               // 检查 IPv4 或 IPv6 格式
      isIPv4: true,             // 检查 IPv4
      isIPv6: true,             // 检查 IPv6
      isAlpha: true,            // 不能使用字母
      isAlphanumeric: true,     // 只允许字母数字字符
      isNumeric: true,          // 只能使用数字
      isInt: true,              // 只能是整数
      isFloat: true,            // 只能是浮点数
      isDecimal: true,          // 检查数字
      isLowercase: true,        // 检查小写字母
      isUppercase: true,        // 检查大写字母
      notNull: true,            // 不允许null
      isNull: true,             // 只能为null
      notEmpty: true,           // 不能空字符串
      equals: 'specific value', // 只能使用指定值
      contains: 'foo',          // 必须包含子字符串
      notIn: [['foo', 'bar']],  // 不能是数组中的任意一个值
      isIn: [['foo', 'bar']],   // 只能是数组中的任意一个值
      notContains: 'bar',       // 不能包含子字符串
      len: [2, 10],              // 值的长度必在 2 和 10 之间
      isUUID: 4,                // 只能是UUID
      isDate: true,             // 只能是日期字符串
      isAfter: "2011-11-05",    // 只能使用指定日期之后的时间
      isBefore: "2011-11-05",   // 只能使用指定日期之前的时间
      max: 23,                  // 允许的最大值
      min: 23,                  // 允许的最小值
      isArray: true,            // 不能使用数组
      isCreditCard: true,       // 检查是有效的信用卡

      // 也可以自定义验证:
      isEven: function(value) {
        if(parseInt(value) % 2 != 0) {
          throw new Error('Only even values are allowed!')
        // we also are in the model's context here, so this.otherField
        // would get the value of otherField if it existed
        }
      }
    }
  }
});

更多参考资料