Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client Side MVC Frameworks (Backbone, Knockout, etc.) and Validation

I am experimenting with different client side MVC frameworks right now (mainly Backbone and Knockout). I am trying to come up with a way to validate. I have MVC 4 Web API that returns data only. All view engine logic is on the client side. Obviously, I understand that server-side validation is a must. This, I achieve with DataAnnotations and standard ASP.NET MVC validation through model binding.

However, I ended up with duplicating all validation logic now on the client side as well. Is there a way to return data but with validation logic attached to it?

like image 670
Nachiket Mehta Avatar asked May 25 '12 18:05

Nachiket Mehta


1 Answers

Blast-Dan is partially right, meaning that you cannot pass extra data to your server from the client aside from Key-Value pairs.

What you can do, however, is propagate your DataAnnotations to the client so that some validation code does not need to be rewritten. It is not trivial for complex rules, but the Html.EditorFor helpers will help you generate text boxes for input with attached validation attributes that are picked up seamlessly by jquery validation and stop the form submitting. I am thinking about [Required], [Range()] and [RegularExpression()] Data Annotations to name a few.

You can see a quick example if you just create a normal model and then add the Controller in Visual Studio using the wizard to create the Views for CRUD operations. You will see how the Data Annotations you used in the Model class end up being rendered on the output html.

If you are creating the HTML yourself without HtmlHelper (which I think you may be doin given the knockout tag) you may want to check the DataAnnotationsModelValidatorProvider and the IClientValidatable interface starting from this link.

As you can see, this is still uncharted territory tho :/

like image 166
Tallmaris Avatar answered Oct 02 '22 15:10

Tallmaris