可能在未指定的元素上“验证”失败?

Possible to have `validate` fail on not specified elements?

以下 returns 成功,即使 obj 包含架构中不存在的元素。

问题

当它看到架构中未指定的元素时,是否有可能 validate 失败?

Jest 有这个 expect(obj1).toEqual(obj2).

如果 Validate 无法执行此操作,那么我必须使用哪些选项来检测不需要的元素?

const Schema = require("validate");

const obj = {good: "1", bad: "2"};

const user = new Schema({
  good: {
    type: String,
    required: true,
  }
});

const r = user.validate(obj);
console.log(r);

是的,Schema 上有一个 strict 选项,来自 documentation:

Schema

A Schema defines the structure that objects should be validated against.

Parameters
  • obj schema definition
  • opts options
    • opts.typecast

    • opts.strip

    • opts.strict

      Validation fails when object contains properties not defined in the schema (optional, default false)

所以你需要这样的东西:

const options = { strict: true };

const user = new Schema({
  good: {
    type: String,
    required: true,
  }
}, options);