asp.net-mvc - ASP.NET MVC : Is Data Annotation Validation Enough?

标签 asp.net-mvc validation asp.net-mvc-2 data-annotations

我在 ASP.NET MVC 2 中广泛使用 Data Annotation 验证。这个新功能节省了大量时间,因为我现在能够在一个地方定义客户端验证和服务器端验证。然而,当我做一些详细的测试时,我意识到如果我只依赖数据注释验证,那么有人很容易绕过服务器端验证。例如,如果我通过使用 [Required] 属性注释属性来定义一个必填字段,并在表单中为该必填字段放置一个文本框,用户可以简单地从 DOM 中删除该文本框(这可以通过 Firebug 轻松完成)现在,在 Controller 内部的 ModelBinding 期间,不会在该属性上触发 Data Annotation 验证。为确保触发“必需”验证,我可以在 ModelBinding 发生后重复验证,但随后我将重复验证逻辑。

大家对验证有什么建议?数据注释验证是否足够?或者是否需要重复验证以确保在所有情况下都会触发验证?

后续评论:
根据下面的答案,我似乎不能单独依赖模型绑定(bind)器和数据注释验证。由于我们得出的结论是需要额外的服务器端验证,我的服务层是否有一种简单的方法可以根据数据注释中定义的内容触发验证?似乎这将使我们两全其美……我们不需要重复验证代码,但即使 Model Binder 没有触发验证,我们仍将确保执行验证。

我将把这个后续评论作为一个单独的问题发布,因为它提出的问题与原来的问题不同。

最佳答案

见代码项目Server-side Input Validation using Data Annotations

Input validation can be done automatically on the client side in ASP.NET MVC or explicitly validating the model against the rules. This tip will describe how it can be done manually on the server-side of an ASP.NET applications or within the repository code of WPF applications.

        // Use the ValidationContext to validate the Product model against the product data annotations
        // before saving it to the database
        var validationContext = new ValidationContext(productViewModel, serviceProvider: null, items:null);
        var validationResults = new List<ValidationResult>();

        var isValid = Validator.TryValidateObject(productViewModel, validationContext,validationResults, true);

关于asp.net-mvc - ASP.NET MVC : Is Data Annotation Validation Enough?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1558457/

相关文章:

c# - 持久 Entity Framework 查询缓存

asp.net-mvc - CQRS中创建聚合根的指导

c# - System.Web.Mvc.HtmlHelper 不包含 MvcSiteMap 的定义

c# - 如何检查用户是否已存在于 ASP.NET MVC 5 的客户端?

javascript - Validate.JS - 禁止使用非 ASCII Unicode 字符

validation - 我应该在 JSF 1.2/2.0/2.1 中使用什么 DTD 来验证我的配置 XML?

php - Laravel 验证正则表达式,中断 View

nhibernate - 何时在 ASP.NET MVC 2 应用程序中提交 NHibernate 事务?

asp.net-mvc - MVCContrib 网格在空时显示标题?

asp.net-mvc-2 - 使用jquery从动态html表中删除一行