【问题标题】:Extends all Joi Validation Package from one file and Import all with const Joi = require('joi')从一个文件扩展所有 Joi 验证包并使用 const Joi = require('joi') 导入所有
【发布时间】:2019-02-25 07:35:18
【问题描述】:

如何将joi-phone-number 像joi-object example 这样的包导出到一个文件下,然后导入使用如下?以下是我的validation.js 和index.js 中的导入。

// validation.js
const Joi = require('joi');
module.exports = function({
  Joi.objectId = require('joi-objectid')(Joi);
  // Here i want to import phone number validation.
})

现在,我创建了两个常量来验证 objectid 和 handphone。

// schema.js
const Joi = require('joi');
const MyJoi = Joi.extend(require('joi-phone-number')); // I want to add this line in validation.js.
exports.validate = function(data) {
   const schema = {
       name: MyJoi.string().required(),
       hp: MyJoi.string().phoneNumber({ defaultCountry: 'US', format: 'e164})
   }
}

我想将所有 Joi 包放在一个文件中并导入该文件以使用不同类型的验证。

// What I want to achieve
const Joi = require('joi)
exports.validate = function(data) {
   const schema = {
       id: Joi.ObjectId(),
       name: Joi.string().required(),
       hp: Joi.string().phoneNumber()
       }
}

【问题讨论】:

    标签: javascript node.js validation joi


    【解决方案1】:

    joi-objectId 看起来很旧并且没有使用Joi.extend() api。您可以简化事情并使自己摆脱这种依赖。它唯一做的就是用以下内容验证一个字符串:

    Joi.string().regex(/^[0-9a-fA-F]{24}$/);
    
    // validate.js
    const Joi = require("joi");
    const MyJoi = Joi.extend(require("joi-phone-number"));
    
    exports.validate = function (data) {
      const schema = {
        id: MyJoi.string().regex(/^[0-9a-fA-F]{24}$/),
        name: MyJoi.string().required(),
        hp: MyJoi.string().phoneNumber()
      };
    
      return MyJoi.validate(data, schema);
    };
    

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 2019-07-08
      • 2018-09-24
      • 2018-02-03
      • 2014-12-18
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多