我正在开发一个来自 PHP 的验证器库,我想为验证提供一个类似的设置,包括验证器和约束(值、对象由验证器针对选定的约束进行验证)。
所以处理约束我有以下问题:
约束都具有相同的属性,只是实现略有不同。
例子:
Constraint = Validator.Constraint = {
name: null, // contains the name of the constraint
value: null, // contains the value which we want to validate
options: {}, // contains options for some Constraints (e.g. range)
message: null, // contains the error message which is getting returned
validate: function(){}, // the validation logic
constructor: function(value, options){
this.value = value;
this.options = options;
this.validate();
} // the constructor which can be called for stand-alone validation
};
现在我想以某种方式扩展约束并对其进行自定义:
RequiredConstraint = Validator.RequiredConstraint = {
name: "required",
message: "this property is required",
validate: function(){
if (this.value != "" || this.value != undefined || this.value != null) {
return;
}
return this.message;
}
// other properties get inherited
};
然后该约束应该可用于:
RequiredConstraint("");
// returns false
我知道想知道两件事:
- 起初,如果完全推荐使用这种编程风格,即使 JavaScript 是另一种语言并且过于动态?
- 如果它仍然是很好的实践,我该如何实现上述行为?我必须寻找哪些关键字?
问候