我有一类在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;
  }
}

最佳答案

尝试类似的操作-在实例化时将对象验证为一个属性,从每个验证调用返回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);

09-11 05:37