javascript - 如何在 JS es6 类中实现多个方法?
问题描述
我有一类在 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;
}
}
解决方案
创建一个具有流利方法/可链接方法的类,该 returnthis
是该类本身的一个实例,当您最终根据规则运行验证时, call.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}`);
推荐阅读
- python - 如何在 Python/Django 中过滤图表(Chart.js)中的日期?
- keras - 文件扩展名 .h5 .hdf5 和 .ckpt 有什么区别,我应该使用哪一个?
- pandas - 对堆叠框架的值进行排序
- laravel - laravel 可以包含路由而不是刀片吗?
- flutter - 如何在颤动中制作自定义按钮形状
- android - Android 改造 API ID
- html - 如何使用 jquery 通过数组从下拉列表中仅获取两个选项?
- webview - 如何在 Webview 中实现我的 Twilio-VideoCall 编程?
- javascript - 在联系表 7 中动态添加 WordPress 帖子标题
- shopware - 购物体验中的 Shopware 6 链接网站