简体   繁体   English

如何验证 json 对象字段是否与 nodeJS tv4 验证库相等?

[英]How to validate that json object fields are equal with nodeJS tv4 validation lib?

I'm writing code for validation of json request for user creation method.我正在编写用于验证用户创建方法的 json 请求的代码。 Validator have to check whether the email field is equal to field confirmEmail.验证器必须检查电子邮件字段是否等于字段确认电子邮件。 Request example:请求示例:

{
     "firstName":"Homer",
     "lastName":"Simpson", 
     "email":"test1234@fox.com",
     "confirmEmail":"test1234@fox.com",
     ...
}

I'm using the tv4 schema validation lib.我正在使用 tv4 模式验证库。 The goal is to write a schema to validate equality between email and confirmEmail fields.目标是编写一个模式来验证 email 和 confirmEmail 字段之间的相等性。

Of course I can check the those fields in request directly but I'd use it as last resort in case schema validation will not work.当然,我可以直接检查请求中的这些字段,但我会将其用作万一模式验证不起作用的最后手段。

You can not test equality of values between properties with json-schema.您无法使用 json-schema 测试属性之间值的相等性。 Json-schema is used to validate json structure. json-schema 用于验证 json 结构。

You can test that those fields exist and that they are correct emails through regex.您可以通过正则表达式测试这些字段是否存在以及它们是否是正确的电子邮件。 You could even test that they belong to a set of predefined values in an enumeration.您甚至可以测试它们是否属于枚举中的一组预定义值。 But nothing else.但没有别的。

In my project, I am using jpv module在我的项目中,我使用jpv模块

const jpv = require('jpv');

const pattern = {
     "firstName" : /.+/,
     "email" : "[email]",
     ...
};

const isVaild =  jpv.validate(obj, pattern)
jpv.validate(data, messageSchema))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM