使用数据注释和JavaScript进行模型/表单验证

时间:2016-06-29 08:17:37

标签: javascript jquery asp.net-mvc validation unobtrusive-validation

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

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

然后会变成类似

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

我可以使用jquery unobtrusive验证来验证它,但是,这个项目没有jQuery。它是直接从Javascript构建的,我们计划保持这种方式。

有没有办法可以在没有jQuery的情况下做到这一点?

2 个答案:

答案 0 :(得分:1)

因此,根据评论,有些库在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;

验证器可重复使用; if 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示例。

答案 1 :(得分:0)

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