【问题标题】:Why is validate.errors empty after this custom keyword validation?为什么在此自定义关键字验证后 validate.errors 为空?
【发布时间】:2019-06-18 19:15:50
【问题描述】:

我正在使用一对自定义关键字来缓解我们的验证需求。到目前为止,它在所有地方都运行良好......但现在我没有让错误持续存在并在验证后被检测到。

ajv.addKeyword('batch', {
    compile: function validator(batch) {
        const { limit, items } = batch;

        const arraySchema = {
            type: 'array',
            items,
            minItems: 1,
            maxItems: limit,
        };

        return ajv.compile({
            oneOf: [
                arraySchema,
                items,
            ],
        });
    },
    errors: false,
});

ajv.addKeyword('customValidator', {
    type: 'string',
    validate: function validate(schema, data) {
        try {
            if (data.length > 500) {
                throw new Error('should be <= 500 characters');
            }
            const { type } = myCustomValidator.parse(data);

            if (schema === true || schema.includes(type)) {
                return true;
            }
            throw new TypeError(`${data} must be one of the following: ${schema}`);
        } catch (error) {

            if (!validate.errors) {
                validate.errors = [];
            }
            validate.errors.push(error);
            return false;
        }
    },
    errors: true,
});

然后是这样的架构:

{
    type: 'object',
    required: [
        'requiredFieldName',
    ],
    properties: {
        requiredFieldName: {
            batch: {
                items: { customValidator: ['allowedType'] },
                limit: 100,
            },
        },
        optionalFields: { customValidator: ['allowedType1', 'allowedType2'] },
    },
}

然后我创建了一个测试失败,导致myCustomValidator.parse 抛出。

{
  requiredFieldName: ['blah', 'blah'],
}

使用console.log,我可以看到它正在抛出并被捕获并被添加到validator.errors。我预计验证会失败,但最终它说它通过了。关于我做错了什么的任何想法?

注意:如果我将架构的batchitems 的定义更改为type: 'integer',它将按预期失败。

【问题讨论】:

    标签: javascript ajv


    【解决方案1】:

    如果你在架构中指定type: 'string'customValidator,那么它会起作用:

    {
        type: 'object',
        required: [
            'requiredFieldName',
        ],
        properties: {
            requiredFieldName: {
                batch: {
                    items: { type: 'string', customValidator: ['allowedType'] },
                    limit: 100,
                },
            },
            optionalFields: { customValidator: ['allowedType1', 'allowedType2'] },
        },
    }
    

    不知道为什么,但是现在可以了。

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2021-02-17
      • 2013-10-29
      • 2014-06-02
      • 2011-05-28
      • 2011-09-15
      相关资源
      最近更新 更多