假设我有以下架构:
var schema = {
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().required()
};
是否可以设置验证规则,检查两个字段是否具有不同的值?
答案 0 :(得分:10)
是的。您可以使用Joi.ref
和Joi.invalid
(别名为Joi.disallow
)来完成此操作。对于您的特定示例,它将是:
var assert = require('assert');
var Joi = require('joi');
var schema = Joi.object().keys({
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().disallow(Joi.ref('fieldOne')).required()
});
测试它会让我们得到我们期望的结果:
assert.ok(Joi.validate(4, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'a' }, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'b' }, schema).error === null);
它的工作原理是在fieldOne
的定义中引用fieldTwo
并禁止使用相同的值。
答案 1 :(得分:0)
不幸的是,我不确定是否存在针对不同值的直接验证,但您可以尝试使用array#unique()
代替:
var xmlreqc=XMLHttpRequest;
XMLHttpRequest = function() {
this.xhr = new xmlreqc();
return this;
};
XMLHttpRequest.prototype.open = function (method, url, async) {
return this.xhr.open(method, url, async); //send it on
};
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
this.xhr.setRequestHeader(header, value);
};
XMLHttpRequest.prototype.getAllResponseHeaders = function() {
console.log( this.xhr.getAllResponseHeaders());
return this.xhr.getAllResponseHeaders();
};
XMLHttpRequest.prototype.send = function(postBody) {
// steal the request
nRemAjax++;
// do the real transmission
var myXHR = this;
this.xhr.onreadystatechange = function() { myXHR.onreadystatechangefunction();};
this.xhr.send(postBody);
};
XMLHttpRequest.prototype.onreadystatechangefunction = function()
{
try {
this.readyState = this.xhr.readyState;
this.responseText = this.xhr.responseText;
console.log(this.xhr.responseText); // this line log json data though
this.responseXML = this.xhr.responseXML;
this.status = this.xhr.status;
this.statusText = this.xhr.statusText;
}
catch(e){
}
if (this.onreadystatechange)
this.onreadystatechange();
//do my logging
if (this.xhr.readyState == 4)
{
nRemAjax--;
// only when done steal the response
consoleLog("I'm finished");
}
};
并在验证前设置var schema = {
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().required(),
fieldOneAndTwo: Joi.array().unique()
};
。