views:

203

answers:

1

I was reading this blog post on ASP.NET MVC 2's new model validation and found it to be pretty cool. I see the value in keeping things DRY by adding a couple attributes to a class property and then automagically getting client and server side validation (as long as your controller checks for valid models).

That said, imagine an ASP.NET MVC application in a greater context. Perhaps I have an ASP.NET MVC application with this validation and all, but then I want to expose things to new clients, like an iPhone or Android application (not just a mobile browser). I would have to write some web-services or something that use the same underlying repositories/services that my ASP.NET MVC app uses. Could I re-use this validation stuff?

Wouldn't I have to re-write the client-side validation? I don't see a way around this, since I'll be shipping off serialized objects to be de-serialized into non-C# classes from Objective-C or whatever.

Wouldn't I also have to re-write the server-side validation? Is there some way for me to call into the ModelState on an object outside the context of an ASP.NET MVC controller (e.g., as part of the web-services I create to talk to mobile clients).

+1  A: 

Assuming you are talking about Data Annotations, they are not part of MVC actually. So you can use them elsewhere as you wish.

There are other work extending them - annotationscontrib is one of them and I guess you can look at how, for example ModelBinder is implemented and write your own service using that.

xVal Project is possibly doing along the same lines as what you are after - converting the validation rules into Javascript. Unfortunately I am not sure how much effort you need to adapt xVal for your project or rewrite it.

As for running the validations on the annotated classes one can use the Validator (thanks womp)

Maxwell Troy Milton King
Yes, it's using Data Annotations. But first, can I use these in any way outside of c# (e.g., in objective-c for iPhone). And second, how to I validate an object based on it's Data Annotations?
manu08
You need to use reflection and scan your annotated classes.
Maxwell Troy Milton King
@Maxwell: Seems weird that I'd have to reflect in myself. I'll keep looking, but that is something I can write if I need to, and share amongst the web services.
manu08
@Maxwell - that is incorrect. You can use the Validator class to manually run validation on data annotations. http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator_members%28VS.95%29.aspx
womp
@womp - thanks. I think this is what I'm looking for. I'll give it a try later. That will at least allow me to easily validate objects coming in from the web services.
manu08
Thanks womp. Sorry about the rubbish reflection comment. Should I delete it?
Maxwell Troy Milton King