因此,根据评论,有些库在 Javascript 中实现模型验证。我写了一个,Egkyron,并在我的工作中使用它。使用这些库,您可以定义模型的验证规则,而不是 UI,就像在服务器端一样。
假设在 JS 中定义的 User 模型为:
function User() {
this.userName = null;
this.password = null;
this.passwordVerification = null;
}
您可以将其验证规则定义为等效于 JS 注释:
User.validators = {
// key is property name from the object; value is the validation rules
userName: [
// the userName is required...
'required',
// ...and some arbitrary rules for demonstrating:
// "the user name starts with a lower-case letter and consists only of lower-case letters and numbers"
['regexp', {re: /^[a-z][a-z0-9]*$/}],
// "the length of the user name is between 5 and 8 characters (inclusive)"
['length', {min: 5, max: 8}]
]
};
如果使用 Babel 或 Typescript,您可以查看装饰器,这是 ES7 规范的提议。一个 TS 类可以注释为:
class User {
@Required()
@RegExp(/^[a-z][a-z0-9]*$/)
@Length({min: 5, max: 8})
userName: string;
...
}
这与您在服务器端使用 Java 或 C# 编写的内容非常接近。事实上,在之前的项目中,我们生成了来自服务器端 C# 类的 JS 类 + 验证规则。
然后,假设您持有 User 对象,您可以使用 Egkyron 验证它:
var validator = new egkyron.Validator(/* see the example for constructor arguments */);
var user = ...; // instance of a User
var validationResult = validator.validate(user).result;
验证器是可重用的;如果user = new User()validationResult 看起来像:
{ // validation result for the given User
_thisValid: true, // no validation rules of **this** object failed
_validity: null, // there are no validation rules for this object (only for its properties)
_childrenValid: false, // its properties and/or children objects are invalid
_children: { // detailed report of its children objects/properties
userName: { // child property name
_thisValid: false, // the userName is invalid (required but not given)
_children: null, // terminal node, no children
_validity: { // detailed report about each validation rule
required: { isValid: false, ... }, // the "required" constraint failed
regexp: { isValid: true, ... }, // empty value => regexp validity defaults to true
length: { isValid: true, ... } // empty value => length validity defaults to true
}
},
...
}
}
获得验证结果后,您可能希望将其呈现给 UI。有无数不同的要求和微小的变化。我相信不可能让所有人都满意。即使我们能够满足所有这些要求,库的大小也会非常庞大,而且很可能库本身并不能真正使用。
因此,Egkyron 将 UI 集成留给了用户。有例子,我很乐意回答任何问题/问题。
除了examples,这里还有一个plunk,上面带有纯浏览器JS示例。