MVC3 unobtrusive validation without data annotations

1k Views Asked by At

I need to create html in MVC3 from dynamic content. My scenario is that I need to create a view that can change the html fields that it displays depending on the user and circumstances. The possible range of fields is not known until we are ready to retrieve them for use and can change. This basic functionality is fairly easy in MVC. However, I want to use unobtrusive client side validation which is where my problem arises.

This is the scenario: I have a list of complex types in the model. The complex type instance stores the metadata about the html field that needs to be created. For example, the complex type has a DataType string property that tells us the html element type to create. "Text" for input element of textbox, "checkbox" for input element of checkbox, "Select" for a select element and so on. The complex type has properties such as Readonly, IsRequired, Value, Regex, MinLength, MaxLength etc... It contains everything we need to create a range of HTML elements and have validation on those elements.

So the list of complex types is inserted into our model in the controller and then we call our view. The view needs to show the appropriate html element taking into account the settings in the complex type for each complex type in the list. This can be achieved by creating a new helper to manage the complex type or having a switch statement in a loop in the view that checks the complex type's DataType and uses the appropriate helper. So far so good.

However, the problem arises where we want to use client side validation without having to create the JavaScript client side unobtrusive attributes ourself which is what I would like to achieve. Is there a way that I can use the existing MVC code to create unobtrusive client side validation without using data annotations?

E.g. Overwrite the existing ModelMetadataProvider DataAnnotationsModelMetadataProvider and call a new method from my own helper.

What would be the best way to achieve the above scenario?

1

There are 1 best solutions below

0
On

How exactly are you creating "dynamic MVC3 html"? Do you mean you're just creating html without using an actual view? Since validation is handled server-side in the model binder (not in the html) dynamic html doesn't make a difference. Client-side, you would just add the data-* attributes to make it work.

Since you've not provided any context upon which your html looks like, we can't begin to tell you how to accomplish what you want.