Model/Form 使用数据注释和 JavaScript 进行验证

Model/Form validation using Data Annotations and JavaScript

我想在我的 ASP MVC 应用程序上实施数据验证。我目前正在使用这样的数据注释:

[Required]
public string UserName { get; set; }

然后会变成类似

的东西
<input type='text' ... data-required>

我可以使用 jquery 不显眼的验证来很好地验证它,但是,这个项目没有 jQuery。它是直接从 Javascript 构建的,我们计划保持这种状态。

没有 jQuery 有什么方法可以做到这一点吗?

如果您想要客户端验证,您必须为 data-**** 标签编写自己的库以验证输入或考虑添加 JQuery Unobtrusive Validation。

因此,根据评论,有库在 Java 脚本中实现模型验证。我写了一个,Egkyron,并在我的工作中使用它。使用这些库,您可以为模型定义验证规则,而不是 UI,就像在服务器端一样。

假设一个User模型在JS中定义为:

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 可以注释为:

class User {
    @Required()
    @RegExp(/^[a-z][a-z0-9]*$/)
    @Length({min: 5, max: 8})
    userName: string;
    ...
}

这与您使用 Java 或 C# 在服务器端编写的内容非常接近。事实上,在之前的项目中,我们 生成 JS classes + 来自服务器端 C# classes.

的验证规则

然后,假设您获得了一个 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() 验证结果如下所示:

{   // 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 集成留给了用户。有例子,我会很乐意回答任何 questions/issues.

除了上面的普通浏览器 JS 示例 examples, here is a plunk