I have written some extension methods that extend the html helper class for client side form validation. What I’d like to be able to do is have the page loaded with an array (javascript) of all of my elements that are part of my validation “library”.
example:
@Html.VTextBox("blah)
@Html.VDropDownList("bling")
@Html.VTextBox("bloo")
when the page is loaded, I’d like a javascript array placed at the top filled with something like this:
errorListArr = new Array("blah","bling","bloo");
Currently what I’m doing is using errorListArr.push() for each element and writing out script tags each time … clearly not the most elegant way to do this. I’d also like to figure out how I can parse the whole page ahead of time so that I can put together my list of elements that I’m going to need to validate server side.
Please let me know if this can be done and any code snippet/samples would be appreciated.
I’m not entirely clear on what you’re trying to do, but I think I understand enough to point you in the right direction.
First of all, server-side validation in MVC 3 is typically done as a postback to an action that takes a model and validates it. If the model isn’t valid, you return the view with the (now-validated) model, and the view will render the appropriate error messages for the properties that were wrong.
By default, you can define what validation to perform by adding certain attributes to the properties on the model that you’re rendering inputs for.
What’s more, MVC is smart enough to output client-side javascript to perform many of these validations when the user tries to submit the form, without actually requiring a post-back at all!
See this post for a walk-through of how to use model validation.
In MVC 3, you also have the option to enable “unobtrusive javascript” validation, which basically does the same client-side validation as usual, but instead of generating a bunch of inline javascript, it simply flags the input elements with certain “data-” attributes. A couple of jquery-based libraries then scan the page for elements with these flags, and add the appropriate validation handlers to them.
If you have validation needs that go beyond what MVC offers out of the box, it is easy to add your own validation attributes, or even make your model perform custom logic to validate itself.
Generally speaking, if you find that you’re rendering a lot of little javascript snippets client-side, you may want to follow the “unobtrusive javascript” pattern yourself: