根据其他字段的数据进行自定义验证

huangapple go评论67阅读模式
英文:

joi custom validation depending on other field's data

问题

我正在尝试创建一个自定义验证规则(在node.js应用程序中使用JOI验证库),该规则依赖于表单的其他字段。

例如:如果emailmobile字段都为空,我需要username字段为必填,反之亦然。

我已经尝试过库本身提供的whenor方法,并在谷歌上搜索过,但仍然没有解决这个问题。

示例代码如下:

const validations = joi.object({
    ...
    username: joi.any().when('email', {
        is: '' || null || undefined,
        then: joi.required()
    }),
    email: joi.any().optional(),
    mobile: joi.any().optional(),
    ...
}).options({
    abortEarly: false
});

或者示例:

const validations = joi.object({
    ...
    username: joi.any(),
    email: joi.any(),
    mobile: joi.any(),
    ...
}).or('username', 'email', 'mobile').options({
    abortEarly: false
});

请帮助,这个问题已经花费了我太多时间。

英文:

I am trying to create a custom validation rule (using the JOI validations library in a node.js application) that dependent of other fields of the form.

For example: I need the username field to be required if both of the email or mobile fields are empty or visa versa.

I have already tried the when and or methods, provided by the library itself and searched on the google as well. But, still standing on same place.

When example:

const validations = joi.object({
    ...
    username: joi.any().when('email', {
        is: '' || null || undefined,
        then: joi.required()
    }),
    email: joi.any().optional(),
    mobile: joi.any().optional(),
    ...
}).options({
    abortEarly: false
});

Or Example:

const validations = joi.object({
    ...
    username: joi.any(),
    email: joi.any(),
    mobile: joi.any(),
    ...
}).or('username', 'email', 'mobile').options({
    abortEarly: false
});

Please help, this issue has already cost me too much time.

答案1

得分: 0

以下是您的工作代码的翻译:

export default (req, res, next) => {
    const validations = joi.object({
        ...
        email: joi.any().custom((value, helper) => {
            if (!value && !req.body.username && !req.body.mobile) {
                return helper.message('Required field');
            }

            return true;
        }),
        mobile: joi.any().custom((value, helper) => {
            if (!value && !req.body.username && !req.body.email) {
                return helper.message('Required field');
            }

            return true;
        }),
        username: joi.any().custom((value, helper) => {
            if (!value && !req.body.email && !req.body.mobile) {
                return helper.message('Required field');
            }

            return true;
        }),
        ...
    }).options({
        abortEarly: false
    });

    const { error } = validations.validate({
        ...
        email: body.email ? body.email : null,
        mobile: body.mobile ? body.mobile : null,
        username: body.username ? body.username : null,
        ...
    });

    if (error) {
        return res.status(406).send({ ... });
    }

    next();
}

希望这对面临类似情况的人有所帮助。

英文:

Here is my working code:

Reference: https://stackoverflow.com/questions/58425499/how-to-add-custom-validator-function-in-joi/61638633#64233670

export default (req, res, next) => {
    const validations = joi.object({
        ...
        email: joi.any().custom((value, helper) => {
            if (! value && ! req.body.username && ! req.body.mobile) {
                return helper.message('Required field');
            }

            return true;
        }),
        mobile: joi.any().custom((value, helper) => {
            if (! value && ! req.body.username && ! req.body.email) {
                return helper.message('Required field');
            }

            return true;
        }),
        username: joi.any().custom((value, helper) => {
            if (! value && ! req.body.email && ! req.body.mobile) {
                return helper.message('Required field');
            }

            return true;
        }),
        ...
    }).options({
        abortEarly: false
    });

    const { error } = validations.validate({
        ...
        email: body.email ? body.email : null,
        mobile: body.mobile ? body.mobile : null,
        username: body.username ? body.username : null,
        ...
    });

    if (error) {
        return res.status(406).send({ ... });
    }

    next();
}

I hope this can help someone, facing the situation like this.

huangapple
  • 本文由 发表于 2023年6月12日 17:06:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455104.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定