开发者

IValidatableObject in MVC3 - client side validation

开发者 https://www.devze.com 2023-02-05 13:03 出处:网络
With MVC3 you have two new mechanisms for adding custom validation. These are (1) subclass ValidationAttribute or (2) implement IValidatableObject.

With MVC3 you have two new mechanisms for adding custom validation. These are (1) subclass ValidationAttribute or (2) implement IValidatableObject.

The ValidationAttribute allows you to add client side validation relatively simply by implementing IClientValidatable (and registering a new adapter and method via jQuery).

IValidatableObject is more suited to one-off validation requirements where reuse is not an option. It also results in slighlty simpler code. It would therefore be my choice for a number of scenarios. Unfortunately, I do not see an easy way of implementing client side validation using this method.

So the question is what am I missing and how DO you get JS validation开发者_运维知识库 when using IValidatableObject?


As I did not get a (valid) answer here, I asked a couple of people from Microsoft and they confirmed that it was not currently possible.

Brad Wilson:

At this time, only property level validators can emit client-side validation (as that lines up much better with the idea of input validation in the form of the browser... there is no "model" to speak of, from the browser's point of view).

Stuart Leeks:

I don't believe you can hook up client validation with IValidatableObject


http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx http://blogs.msdn.com/b/stuartleeks/archive/2010/07/28/asp-net-mvc-adding-client-side-validation-to-validatepasswordlengthattribute-in-asp-net-mvc-3-preview-1.aspx

ASP.NET MVC 3 now honors the IValidateObject interface when model binding (in addition to all of the other validation approaches it already supported with MVC 2), and will retrieve validation errors from it and automatically flag/highlight impacted fields within a view using the built-in HTML form helpers.

ASP.NET MVC 3 also introduces a new IClientValidatable interface that allows ASP.NET MVC to discover at runtime whether a validator has support for client validation. This interface has been designed so that it can be integrated with a variety of validation frameworks. MVC 3 also introduces a new IMetadataAware interface that simplifies how you can contribute to the ModelMetadata creation process.


This article describes a way to access the container object in client side validation in ASP.NET MVC. You can probaly use this to get started on using your own client side validation

0

精彩评论

暂无评论...
验证码 换一张
取 消