我在JS中创建了一类验证:
let test = new Validator(req.body);
现在我想测试一些东西,也许这个对象中的一个特定键是2-5个字符长度,我会这样做:
let myBoolean = test.selector("firstName").minLength(2).maxLength(5);
// firstName is like: req.body.firstName
以及如何在课堂上做到这一点?
编辑
我做了这样的东西:
audit.isLength({selector: "from", gte: 2, lte: 35})
class Validator {
constructor(obj) {
this.obj = obj;
this.isValid = true;
}
isExists(sel) {
if (typeof this.obj[sel] === "undefined") return false;
return true;
}
isLength(info) {
let sel = this.obj[info.selector];
if (typeof sel === "undefined") return false;
if (info.gte) {
if (sel.length<info.gte) return false;
}
if (info.lte) {
if (sel.length>info.lte) return false;
}
if (info.gt) {
if (sel.length<=info.gt) return false;
}
if (info.lt) {
if (sel.length>=info.lt) return false;
}
return true;
}
}
发布于 2018-08-01 04:20:19
使用/创建一个类,返回this
,它是类本身的一个实例,当您最终根据规则运行验证时,调用.validate()
,它将作为返回结果的最终方法:
class Validator {
constructor (body) {
this._body = body;
}
selector(str) {
this._selector = str;
return this;
}
minLength(num) {
this._minLength = num;
return this;
}
maxLength(num) {
this._maxLength = num;
return this;
}
validate() {
// run your validation logic here and return true or false accordingly
return true
}
}
const req = { body: 'body' };
const test = new Validator(req.body);
const myBoolean = test
.selector('firstName')
.minLength(2)
.maxLength(5)
.validate();
console.log('rules:');
console.log(test);
console.log(`result: ${myBoolean}`);
发布于 2018-08-01 04:24:45
尝试这样做-将要验证的对象分配给实例化上的属性,从每次验证调用中返回this
,在验证时,分配给对象上的isValid
属性(如果它还不是false
)。请注意,您最终需要访问isValid
属性才能检索布尔值。
class Validator {
constructor(obj) {
this.obj = obj;
this.isValid = true;
}
selector(sel) {
this.sel = sel;
return this;
}
minLength(min) {
if (this.isValid) this.isValid = this.obj[this.sel].length >= min;
return this;
}
maxLength(max) {
if (this.isValid) this.isValid = this.obj[this.sel].length <= max;
return this;
}
}
const test = new Validator({firstName: 'foobar'}); // 6 chars: invalid
console.log(test.selector("firstName").minLength(2).maxLength(5).isValid);
const test2 = new Validator({firstName: 'fooba'}); // 5 chars: valid
console.log(test2.selector("firstName").minLength(2).maxLength(5).isValid);
const test3 = new Validator({firstName: 'f'}); // 1 char: invalid
console.log(test3.selector("firstName").minLength(2).maxLength(5).isValid);
发布于 2018-08-01 04:17:12
这是构建器模式(某种程度上)。您可能希望定义一个具有minLength和maxLength函数的单独类。这些函数将在构建器上设置一些状态,并返回this
(构建器本身),或者返回一个新的构建器,它是this
的副本。然后在构建器上有一些finalize函数,它查看状态,根据最小/最大值处理所有逻辑,并返回一个布尔值。
https://stackoverflow.com/questions/51621342
复制相似问题