How do you do validation in ASP.NET MVC RC? - asp.net-mvc

Does ASP.NET MVC provide a standard validator functionality or do you have to create your own validation manually? If the latter, is there any third party validator available that you can use on ASP.NET MVC web applications?

Shortly after I posted this answer I found xval which is a validation framework for ASP.NET MVC.

ASP.NET MVC contains methods like Html.ValidationSummary() and Html.ValidationMessage(). These are updated automatically if you use TryUpdateModel. You could also validate manually and set the errormessages yourself. Here is an example of how use it.

David Hayden wrote an article over at www.codebetter.com describing a great way to handle validation. Of course xVal is an option but it's always great to have an understanding.

I implemented a variant of the code I found on Stephen Walther's blog. I use it with LINQ2SQL models by defining an IValidatedEntity interface that includes the GetRuleViolations() method and implementing the partial OnValidate method that calls GetRuleViolations() and throws a custom exception if the number of violations is non-zero. In the controller, this fires on SubmitChanges for the data context. If I get an exception I requery the model via the GetRuleViolations() method to build model errors to pass back to the view.

You can also checkout the .net validation framework. Its a rules framework that lets you create validators, apply the validators to rules, attach rules to your model, and check those rules at runtime on both the client and server. It provides flexible ways to configure rules - making heavy use of linq for both fluent and strongly typed configuration. It also provides extensibility points to create your own client script generators and rules.
The framework leverages the MVC RC HtmlHelpers and default conventions.
If you download the latest source you can see an example of the framework working in the SplitBranch -> QSAspMvc quickstart project. Its still being actively developed.

Related

NHibernate Validator and ASP.NET MVC 4

We're looking at upgrading a large-scale project currently implemented using ASP.NET MVC 2 with xVal providing the glue between NHibernate Validator and client-side validation.
When I was looking for resources on using the new "unobtrusive" client side validation used in MVC 3/4 with NHibernate Validator, I was only able to locate a single (and nearly 3 year-old) blog post about this.
Has anyone successfully used NHibernate Validator for client-side validation in MVC 3/4? If so, what has your experience been?
Although I don't have any experience directly with NHibernate, FluentValidation (a validation framework worth considering itself) has an MVC 3/4 adapter extension project which would serve as an excellent guide to creating an NHibernate Validator implementation.
So, i've never used NHibernate Validator, but consider to, because NHibernate Validator has a better perfomance than native MVC unobtrusive validator(MVC validator is totaly based on reflection, in case of NHibernate Validator reflection work happens at startup only).
In case of a large-scale project, i think it is better way.

MVC Service layer validation within WebForms application

We have a service layer within our MVC3 application using an almost identical approach as described here: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
The service layer doesn't depend on MVC.
The issue is we have a legacy webforms application that needs to also create these services and I'm trying to come up with the best approach on how to instantiate these services. It would also be nice to have the Validate() method return the validation errors.
An individual service requires an IValidationDictionary at construction which within our MVC app we simply use the ModelStateWrapper(this.modelstate) however in Webforms we obviously don't have the concept of ModelState (as in Controller.ModelState)
So my question would be how would you construct a service layer with model validation that can be used within an MVC and Webforms application?
At this stage we're not considering an IoC
On a side note:
Am I missing something obvious with ModelStateDictionary? It's within the MVC namespace but doesn't appear to be dependant on the MVC framework? Isn't it just a wrapper for a Dictionary with a setup?
The ModelStateWrapper is a good approach for MVC but like it's an implementation of the IValidationDictionary. You could do a web form implementation but instead use a validation summary control instead of the model state.
Sorry I don't have any code to show you at this time.

NHibernate.Validator vs DataAnnotations

In my APS.NET MVC project I'm using DataAnnotations for validations.
I moved from L2S to NHibernate orm and in fact found that NHibernate has its own validator (NHibernate.Validator)
Does it make sense to move to NHibernate.Validator as well?
For example DataAnnotations has [Required] attribute and NHibernate.Validator [NotEmpty, NotNull, NotNullNotEmpty] and it makes me think what to use.
I've used both in production projects and, if you have the time to make the switch, I would highly reccomend NHibernate.Validator for a couple of reasons:
NHibernate.Validators has a
richer set of validation attributes
(for example, the handful you
mention above)
If implemented
properly, NHibernate.Validators
validations are easier to unit test.
No. 1 wasn't huge for me, and may not be for you, as the set of attributes in DataAnnotations is pretty complete (and you can fall back to RegEx, if need be), but no. 2 was a big deal for me because I wanted to be able to include data validation as a part of my Domain Model unit tests, as opposed to testing those only through UI/Web testing via WatiN or Selenium. Using Validators also allowed me to mix Domain Model rule validation (Property X OR Y must have a value, but both cannot be null) without having to go to another place to do so.
For some basic guidance on using NHibernate Validators, check out this article: http://nhibernate.info/blog/2009/04/02/nhibernate-validator-and-asp-net-mvc.html, and I would also reccomend getting the source for S#arp Architecture, Billy McCafferty's great framework for creating DDD-style ASP.NET MVC applications. In particular, check out his implementation of Validators and the Validator ModelBinder you'll need to create to transfer NHibernate validation errors into MVC ModelErrors. Download the S#arpArchitecture source here: http://github.com/codai/Sharp-Architecture.
The bottom line is this: Using NHibernate.Validators is the more extensible, testable option, but it will take some doing for you to use it properly. DataAnnotations is baked into the framework and easier to get running with, there's no question about that.
Hope that helps.

Options for asp.net MVC Validation Framework

I'm thinking of two options right now for model-base validation for an ASP.net project I'm starting:
xVal (Steve Sanderson's project) and the Enterprise module that Stephen Walther uses on this page
I don't really know enough to talk about the preferences as I haven't used either of them yet. Any ideas?
Update Using LinqToSql for ORM right now, but am open to changes.
One difference I see in reviewing the two is that Stephen Walther's blog post describes a library which does only validation in the Web server, where as xVal works with jQuery validators to do in-browser validation, as well. This feature, incidentally, is almost completely automatic.
FluentValidation is nice. NHibernate also has built in model validation. Then you need something like Scott Guthrie's technique for binding errors to the UI.
I've been using xVal to and i have integrated it into the IDataErrorInfo interface introduced into MVC RC1. I like it.
Here is a post I wrote which explains a few things.
http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/
Hope this helps.
Shamelessly promote my validation library. Built for jQuery validate & Enterprise Library and work out of the box for just that. That said, functionality and code are simple enough to modify/extend if you want.
You could also check out this new technique on LosTechies http://www.lostechies.com/blogs/hex/archive/2009/06/10/opinionated-input-builders-for-asp-net-mvc-part-5-the-required-input.aspx I like the fact that you inputs are setup globaly which is really DRY. Also you could just skip the client side validation and do an jquery ajax submit form to the server, which performs validation model and business logic all in one place, which is also DRY :) Also it means you will get the product out the door quicker and you can add client side validation later as a bonus or to progressively enhance the forms.
Another vote for xVal. It's real sweet. I like using Buddy Classes and DataAnnotations to do the validation lifting. Outside of making things work with Linq2Sql as you cannot add attributes to your fields, buddy classes give one a bit of flexibility to have multiple models share the same validation info. Comes in real handy for those ModelEditData classes that seem to always become neccessary.
Are you using an ORM? If so, which one are you using? I've had a lot of luck, when using Castle ActiveRecord, simply sticking with their default model-level validation. If you're not using that, though, this is probably not too helpful. :-)

ASP.Net MVC datarow validation

I am delevelopring my first MVC application and I am using a classic ADO.NET dataset as a model. The guide I am following is the NerdDinner ASP.NET MVC Tutorial and it mentions a GetRuleViolations() method for a Linq To SQL model. I would like to have a similar method to check that a datarow is valid after editing. How could I do such a thing?
Datasets are disconnected. As such they don't support validation rules unless you add constraints manually.
Edit: From the link:
We’ll implement IsValid and GetRuleViolations() by adding a “partial class” to our project. Partial classes
can be used to add methods/properties/events to classes maintained by a VS designer (like the Dinner
class generated by the LINQ to SQL designer) and help avoid the tool from messing with our code.
You could do something similar with a typed dataset.
See this link on validation with typed datasets.
I guess you should use the dataset for data transfer only. Not for business rule validation. In this way you can still follow the tutorial and keep the repository. But replace all Linq to SQL code inside of the repository with your own dataset code.
Your business objects will be the ones implementing the GetRuleViolation() method.

Resources