Site Meter

Thoughts on validation in ASP.NET MVC applications

A couple of months back, I supplied some code for doing model-based validation in an ASP.NET MVC application in a way that automatically generates client-side validation JavaScript. That was pretty popular. Lots of people are enthusiastic about expressing validation rules as attributes on model properties. However, ASP.NET MVC has been enhanced since then, and so have my views on what constitutes tidy and effective validation.

So, let’s start with the new technology. MVC Preview 5 comes with two new API pieces that seem relevant to validation:

  • ModelState. Controllers now have an official way to pass validation error information to views. Populate ViewData.ModelState, then you can use the built-in HTML helpers to render error message summaries, and to highlight input fields that correspond to errors.
  • Model binders. Controllers are expected to populate model objects from form posts using the IModelBinder API. You can create custom binders – the framework calls your binder to obtain a value for each model property. (If you don’t understand this, don’t worry – it turns out not to be relevant.)

The obvious thing to do (and I’ve seen several forum posts and blog comments suggest this) is to make a custom model binder that applies validation rules (maybe ones expressed as attributes on model properties, such as [IsRequired]) and populates ModelState with any errors it finds. However, there are technical issues that make such a design unworkable in Preview 5 (model binders don’t get told what type of model object they’re providing values for). And more importantly than the current technical issues, that sort of design would be totally undesirable anyway. Validation has nothing to do with controllers binding form posts to model objects, as I’ll explain.

In the last week, Scott Guthrie posted about handling form posting/validation scenarios in ASP.NET MVC, and so did Stephen Walther. The following design has some things in common with each of their designs, but some important differences too.

Basic principles

So, how do you design a pattern for validation? Like any design, start by deciding what characteristics are really important to you, and build from there. Here’s what I consider to be important truths of validation:

  1. Model objects should perform and enforce validation at the appropriate time.
  2. Validation rules should be expressible in plain old C#.
  3. Validation rules and business rules are at opposite ends of the same spectrum.
  4. Errors should bubble up to the UI automatically (no code needed).
  5. Client-side validation is optional – it’s purely for convenience.

And what does that mean?

[1] says that model objects don’t merely hold validation rules (e.g., as attributes on their properties), but model objects also actually enforce those rules. So, it’s not acceptable for a controller class to make the decision to validate (as they do in many other examples) – that would undermine the model’s encapsulation, and would mean that a badly-behaved controller could choose to skip validation. It’s the model that enforces validation, and it does so at a time of its own choosing – usually when something is being committed (e.g., when the model object is being saved to the database), but it might also choose to validate simple property formatting rules during property setters.

Now, if the model is capable of enforcing validation at a time of its own choosing, then it needs a general-purpose mechanism to forcibly abort certain controller operations when validation rules are violated. Fortunately, C# comes with the perfect mechanism: exceptions. There’s nothing clever about this (simplicity is the goal) – when the model decides it won’t allow an operation, it throws an exception. The operation is forcibly aborted. The controller must obey.

Also, bear in mind that certain validation rules can only be enforced at the point of committing data or finalizing actions. For example, “usernames must be unique” will probably be enforced in your database (with a UNIQUE constraint). You therefore can’t rely on a single “validation” moment – the model has to be free to issue rule exceptions at any point during its processing, and the controller shouldn’t need any special-case logic to deal with this. This requirement fits quite easily into the following design.

[2] just says that I don’t want to rely on any kind of rules engine. Now I’m perfectly happy to have reusable attributes to represent certain simple property formatting rules (e.g., [IsRequired], [DataFormat(Formats.EmailAddress)]), and you could even build a custom rules engine, but these are built on the fact that arbitrary C# is allowed.

[3] tries to clarify that simple property formatting rules (e.g., must be valid SSN) are a good start, but not adequate on their own. Certain business rules describe whether or not an operation is allowed (e.g., usernames must be unique), might relate to interactions of multiple properties, might involve arbitrarily complex logic, and these ought to fit into the validation framework too. See the diagram below.


[4] is about making the system easy to maintain. When I add a new validation rule to my model, I want all controllers/views that work on that model type to render suitable error messages automatically, without changing any controller/view code.

Now, remember that when the model decides some rule has been violated, it throws an exception. If that exception is of some special type (let’s call it BusinessRuleException), then that exception can describe in some strongly-typed way which rule was validated and how. In fact, it can describe multiple rule validations simultaneously. All we need now is for controllers to catch BusinessRuleExceptions, use them to populate ViewData.ModelState, then ASP.NET MVC’s built-in helpers will take care of displaying the messages. We can do localization in this step too, for multilingual error messages.

[5] says that it’s nice to have a helper to generate client-side validation code automatically, but the helper doesn’t have to replicate every rule on the client. Obviously, since we’re allowing arbitrary C# rules, there’s no automatic translation of arbitrary rules to JavaScript. Sometimes client-side validation is impossible anyway (e.g., “usernames must be unique”). However, if some simple property formatting rules are implemented as attributes (e.g., [IsRequired]), then we can generate client-side code from these attributes. It won’t cover all rules, but it will cover many of them, and that’s good enough.

Time for some code plz

Yes I know – reading English is hard work. Far easier if I show you some C# code. Here’s how a model class might look:

public class Person
    [Required] [StringLength(20)]
    public string Name { get; set; }
    [Required] [Range(1, 200)]
    public int? Age { get; set; }
    public void EnsureValid()
        // If any of this object's property values conflicts with a validation [Attribute],
        // it will add an entry to the violations collection
        RuleViolations violations = ValidationHelpers.RunValidationAttributes(this);
        // Now we can run any other custom C# validation logic
        if(Age.HasValue && ((DateTime.Now.Year - Age.Value) % 4 == 0))
            violations.Add(new ArbitraryViolation("Age", "Sorry, you were probably born on a leap year, so we won't let you register."));
        if (!violations.IsEmpty)
            throw new BusinessRuleException(violations);
public static class PersonRepository
    public static void SavePerson(Person person)
        // The model is reponsible for deciding when to validation.
        // It chooses to validate now. If there's a violation, it will
        // throw an exception
        // Good - it was valid. Todo: now save to database

As you can see, there are some simple property format rules implemented using attributes (these are the standard ones shipped in System.ComponentModel.DataAnnotations), but these are just a special case. You can of course use arbitrary C# logic when enforcing validation.

I don’t need to have a special method marked as the validation method (or an IValidatable interface or anything like that), because the model layer makes its own decision when to validate, and chooses how to do that. It just has to throw a BusinessRuleException if there’s a problem. In this example, it chooses to enforce validation before writing to the database, but you could choose to validate certain properties during their setter methods if you wanted.

Next, how does a controller look? It follows a general pattern like the following. The critical bit is that model operations are wrapped in a try…catch so that it can recover from errors and display suitable UI feedback.

public class RegistrationController : Controller
    public ViewResult Edit() { return View(new Person()); }
    public ActionResult Edit(string unused)
        Person model = new Person();
            if (!TryUpdateModel(model, new[] { "Name", "Age" })) // At some point it may be possible to have a custom binder that throws a BusinessRuleException if there were setter exceptions, but as of Preview 5, have to use the slightly hacky TryUpdateModel()
                throw new BusinessRuleException();
            // The real validation happens to be enforced by the model here, but that's no concern for the controller
            // The operation completed successfully (so validation must have passed)
            return RedirectToAction("Completed");
        catch (BusinessRuleException ex)
            // Generate suitable localized UI feedback based on exception that was thrown
            // Re-render edit screen
            return View(model);

Notice the call to ex.AddToModelState(ViewData.ModelState);. I’ve implemented that as an extension method on BusinessRuleException (so as not to mix ASP.NET MVC concerns with the core BusinessRuleException class) – it simply iterates through the list of RuleViolations objects, and generates/adds some localized UI feedback to ViewData.ModelState for each violation.

I haven’t included the full source code here because it’s still all a bit proof-of-concept, but it’s not too hard to fill in the gaps and get a working implementation.


And what of client-side validation?

As we discussed earlier, not all rules can be translated to client-side validation code. However, since some of the simpler rules (those on the green end of the validation-businessrule spectrum) are often implemented as System.ComponentModel.DataAnnotations attributes, it would be a straightforward job to make a Html.ClientSideValidation(object model) helper that dynamically generates suitable validation JavaScript. This bit is essentially the same as what I implemented in my previous MVC validation post.

Of course, you could have a pluggable system to generate a JS validation configuration suitable for multiple client-side validation frameworks.

About setter exceptions

As mentioned earlier, sometimes it’s desirable to enforce validation rules in property setters. This gives you solid assurance that your model object can’t have invalid property values, because when *any* code (an MVC controller or model binder, or some other domain or service code) tries to manipulate the model object, they’ll never get away with setting invalid property values. This strategy applies only to simple individual property formatting rules (the green end of the spectrum).

When setters throw exceptions, MVC Preview 5′s DefaultModelBinder is clever enough to capture them one property at a time, building up a ModelState structure. Unfortunately, at present, it disregards the exception type, so you can’t use it to generate suitable UI feedback later. I’ve asked for this to be fixed – let’s be optimistic that the MVC team will give tighter support for setter exceptions in the next update.

Now, here’s an interesting twist. If we want some validation rules to be enforced in setters, and those rules are expressed as [Attributes], then wouldn’t it be cool if that logic was automatically injected into the setter by the attribute? This gets us into aspect-oriented programming territory (AOP). Unfortunately the .NET CLR doesn’t have much support for AOP. PostSharp is the best option we’ve got, but it does require a special code compilation process.

If instead of using the System.ComponentModel.DataAnnotations attributes we used custom attributes, then they could implement PostSharp’s special interfaces. Then, when you compile with PostSharp, the attribute’s simple validation logic can automatically get injected into the property setter. However, if you don’t compile with PostSharp, then the logic wouldn’t automatically get injected into the setter, and you’d cleanly fall back on the behavior I showed earlier in this post.

Of course, this would only be useful if ASP.NET MVC gets better support for setter exceptions.

So, would you do validation like this?

Long post… sorry! Dear readers, I’d be very pleased to hear of any feedback on this design. If there’s any consensus on how it should work, then I or someone else could work it up into a downloadable reusable set of components and classes. This would include:

  • The BusinessRuleException class that you can throw from your model layer to signal and describe arbitrary invalid user actions. It would hold a set of strongly-typed RuleViolation classes (e.g., RequiredFieldViolation, StringLengthViolation) that your controller or view can use to generate localized UI feedback
  • Support for running System.ComponentModel.DataAnnotations attributes against a model object, to produce a collection of RuleViolation objects if there were problems
  • A custom model binder that knows how to generate and throw a suitable BusinessRuleException if there were setter exceptions
  • A helper for generating client-side validation code based on System.ComponentModel.DataAnnotations attributes (perhaps supporting multiple JS validation libraries)

50 Responses to Thoughts on validation in ASP.NET MVC applications

  1. I really like this approach.

  2. robert d

    I second Nick. Simple support for multiple JS validation libraries through attributes would be really nice too!

  3. Chris

    This was a good addition to preview 5. I would personally say the validation belongs IN the model instead of beside the model as binders, but that means forcing models to inherit from a base class or implement an interface, which might not be practical. All in all, ModelBinders are nice and flexible.

  4. Running server-side validation based on System.ComponentModel.DataAnnotations attributes as well as generating client-side validation based on those same attributes would seem the best way to deal with validation.

    Your diagram of the ‘continuous spectrum’ is well thought out, and so it seems that throwing exceptions must be the way for the model to control its own validation whenever it needs to. I agree that the controller should not start the validation, but it should have a good way to deal with the errors when they occur.

    So yes, I would do validation like this, and I have voted on the issue. Thanks for your write-up.

  5. Steve, great post, but I am not sure I like adding the validation in the model. It violates the single responsibility principal because now you have to change the model if your validation changes. Maybe moving the validation to another class such PersonValidator or even a generic validator that uses reflection e.g. Validator

    Anyway, I am writing (yet another) model-based validation post that implements server and client validation. I should have it up in the next few days… Keep an eye out, I would like to get your opinion on it.


  6. Hey there,

    I was about to blog about this as well, I use a similar approach.

    So in my models, they all inherit from the base class which has a function called Validate which returns a list of ValidationRules, There is also another function called IsValid()

    Validations rules contains, message, related fields so on.

    I then wrote a syntax helper for my class so I can do validations like

    Verify.That(Person.Email, Is.Null)
    Similar to nunit

    I then in the controller set a notification class that contains all the validation rules and a message and notification type {Error, Success, None….}

    Then in the views I can set an overall message and set per field messages quite easily by retrieving the notification class and looking for related fields and message.

    Concerning client side javascript, my thought was maybe I could use the syntax helpers in some way, to automatically generate the client side. However I haven’t got that far yet :)

    @Emad, I’ve never thought of it like that? I normally keep in in side a validate method, my assumption is that if a validation was affect the structure of the model, then I would mostly need to change the model anyways.

  7. @Emad: Re “It violates the single responsibility principal because now you have to change the model if your validation changes.”
    You can get around this by defining your rules in either xml or through another assembly using code. I used the xml approach when working with rigid generated model class that did not allow you to easily decorate obejcts with attributes.

  8. Pingback: ASP.NET MVC Application Building: Forums #4 1/2– Validation Revisited - Stephen Walther on ASP.NET MVC

  9. Really great post! — I spent most of today thinking about the same issues and I came to almost the exact same conclusions.

  10. liviu

    Hi, regarding the fact that UpdateModelCore() “hides” exceptions you could overcome this easily.
    define a threadstatic List in a static class.
    Extend the controller with a method TryUpdateAndValidateModel that clears the list, call TryUpdateModel…
    In your validation rules add exceptions also to the threadstatic exception list.
    In this way validation exceptions will be available to

    What ya think?

  11. Steve

    @Nick, @Robert, @michielvoo – thanks!

    @Chris – sorry, not sure if I understand your comment. I never suggested that validation should be part of model binding. This whole post demonstrates another way that doesn’t require model objects to derive from a common base class or implement any particular interface.

    @Emad, @Simon – I’m not arguing that validation has to be embedded in model classes in any particular way, but rather that validation/rules as a whole are a responsibility of the model layer. I don’t mind whether you have partial classes, buddy classes, XML files, attributes, whatever – just suggesting that when the model layer does something (e.g., when a repository is committing something), it should have the power to enforce validation.

    @Cameron – I’ll look forward to reading your post. You mention having all model classes inherit from a common base class exposing an IsValid() function. That’s something I’m trying to avoid, because validation isn’t always just a feature of an isolated domain entity. The notion of validation and rules is more general than that: you might have rules that span multiple entities or are applied differently during different operations. For example, an order state might be valid in the context of one process, but not valid in the context of a different process. If you allow the whole domain layer to control validation (e.g., letting service classes as well as entities enforce rules) then you can account for these scenarios naturally. It wouldn’t be so easy if you have to say that an individual entity state is “valid” or not.

    @Stephen – glad we’ve got some consensus about doing validation and rules enforcement in typical MVC business applications. Thanks for your post.

    @liviu – I’m sure you could come up with a Preview 5-compatible workaround like that. Thanks for the suggestion. I’m still hoping the next MVC release might have a simpler way of retaining setter exceptions.

  12. liviu

    about purity, i think EnsureValid is to be called in a validator manager class. The repository does not have to include also validation magic. the entity should only be tagged with attributes and maybe some custom validation methods.

  13. @liviu I agree

    @steve I see your points and I am going to think about this for a bit and see what I find…

    I agree that the model layer should be responsible for validation but I want to do it in a way that is completely agnostic to the fact that it is an MVC application. So, I don’t want to have dependencies on ModelState or anything MVC-specific.

    I also agree with you that we shouldn’t force the model classes to implement or inherit any class just to do validation… I have to think more about this but I am thinking something along the line of.

    virtual class ModelValidator
    virtual List Validate(T model)
    {//general implementation}
    virtual bool IsValid(T model)
    {//general implementation}
    class UserValidator : ModelValidator
    //override if necessary

    Now, I am struggling with where to call the Validate and IsValid methods… Maybe in the service/BLL layer when saving and updating? This way it sets between the model layer and the controller/application layer.

    I will be back :)

  14. Steve

    > I want to do it in a way that is completely agnostic
    > to the fact that it is an MVC application. So, I don’t
    > want to have dependencies on ModelState or
    > anything MVC-specific.

    @Emad – I think you’ll find that the design I’ve suggested *is* completely ASP.NET MVC agnostic. The model layer has no notion of ModelState – it just throws an exception if it doesn’t want to proceed with some operation. The MVC controller is responsible for handling that exception in some sensible fashion (e.g., using it to populate ModelState). The more I talk about this the more incredibly obvious it all seems. It’s just using exceptions.

    Also, why do you want to formalise standard Validate() and IsValid() methods? There’s nothing wrong with following such a pattern for some of your model entities, but that’s just a special case of the overall strategy. The model layer (which includes service classes/repositories/etc in addition to entities) can choose to impose rules whenever it’s relevant in the context of the operation at hand. Saving entities to a database is just one possible operation.

  15. Pingback: Netbits » Model-based validation for ASP.NET MVC: better approach

  16. Hi Steve,

    I used almost exactly the same on a previous project. We were building on top of Subsonic, and model entities validated themselves and threw exceptions when something went wrong. I like the separation of having entities look after themselves. I think of it in a very similar way to database referential integrity – we *could* choose to do all the validation for foreign keys in an application, but that overlooks the fact that it’s much better structurally to have the database responsible for maintaining its own integrity. As you point out, it’s clearly a continuous scale – no reason to introduce an arbitrary ‘jump’ from one form of validation to another!

  17. Mihai

    I’d like a more fluent approach to this one. The way Data Dynamics requires you to do it is pretty good. I think I’d go more with client side javascript validation, and as a fall back with something like convention over configuration.
    I have no idea how this could be implemented yet but what I’d go for would be kinda Filed(“fieldName”).IsRequired().And().ValueIsNotNull().And().IsAEmailAddress();
    Haven’t put much thought on the matter but going for something in the lines of that would get my juices pumping >:).
    And all the rules to be in a class different than the one inside the domain. For instance ProductConstraints or whatever name that is better thought of :)

  18. Pingback: Client & Server Side Validation in ASP.NET MVC | Emad Ibrahim

  19. Is it possible to have both?

    Also the IsValid function is really only does
    Validate().Count == 0

  20. Fantastically put together post, Steve. I agree with most of what you say here.

    One thing that I’m trying to envision is how we adapt these validation scenarios to leverage both custom validation mechanisms both at the model level and at the client level.

    For example, your attributes are very similar to Castle Validators, which we might leverage, but then we’d have to implement ValidationHelpers.RunValidationAttributes for that.

    And if we used prototype or jQuery UI validators, or possibly the live validation library in javascript, I’d like to see this taking shape where we can pick & choose and just write an adapter for each new one. Easier said than done, I know… but I look to MvcContrib to provide this type of goodness.

    Anyway, great stuff, thanks for this post.

  21. Steve,

    Great post; I agree with almost all your points, especially your notion of validation as a continuous scale, and the idea of auto-generating “simple” client side validation from the same information the server side validation uses (i.e, attributes).

    I’m interested in helping out with any opensource code to implement these ideas – is this something that could be contributed to MvcContrib?

  22. Steve

    @Ben, thanks! I’ve also been trying to work that out, along with a number of other things needed to make a really slick reusable validation framework for ASP.NET MVC. Since arbitrary C# can’t in general be converted to JavaScript, you can’t really expect arbitrary custom validation attributes to automatically map to the relevant implementations in a range of different client-side validation libraries. However, if the client-side helpers can deal with a rich enough set of standard attributes, then it’s a good enough solution. You don’t need to replicate all rules on the client. You could have a “custom rule” attribute that contains both a C# and JavaScript representation of the rule, but it wouldn’t necessarily mesh well with every third-party JS library. Or maybe it would?

    @David – I can’t commit to starting any new projects right now, but if I do find time to go further with this, it will very likely be open source and you’d be welcome to participate. In the meantime, various other people have been providing implementations of this strategy.

  23. Love your site it is very informative am going to research the other posts to see what else I can learn, cheers! and keep up the great work!

  24. Hi Steve,

    I thoroughly enjoyed this post. Especially your continuous validation spectrum.

    I would love to extend your validation approach with Spring.NET’s validation ( and AOP ( framework.

    I have to say I disagree a bit with point [2]. Personally I prefer to abstract away as many business-like rules, into a configurable text medium, that is also expressible in C#. Spring.NET is perfect for this. You can create different validation groups to be called at different stages of the model life cycle. Combine this with a custom validation Aspect that is dynamically wired up, with the correct validation rule, and you’ve truly got a powerful, yet transparent, validation engine.

    A key goal of Spring.NET’s validation engine is that it’s technology agnostic. Meaning you can reuse the same rules from the Windows UI, ASP UI, MVC UI, or from the back-end.

    The only part that’s going to be a bit tricky is the JavaScript client validation …

  25. Steve,

    Very good thoughts…I’ve thought often about how explain the validation concepts you did so easily in your spectrum. The idea that a SSN follows a certain pattern to me is not a business rule but is an intrinsic rule.

    How are you managing more complex interaction in your domain for example? If you annotate your model classes with attributes you have to have something else come along and call the “validate” method as was pointed out.

    I also don’t like “littering” (bad word I know) my domain with attributes which have an outside dependency.

    Seems like the example above is somewhat trivial (forms over data), do you see issues with this for more complex domains?

    Curious on your thoughts?

  26. Steve

    Hi Tim

    I think this approach scales extremely well to more complex domains, because the core of the idea is that validation isn’t just a set of attributes you tag on to model properties – it’s the ability for the domain to signal violations at any stage in any operation. For example, when publishing an article, a CMS could throw a BusinessRuleException because the article hasn’t been approved by a particular manager.

    The attributes-on-model-properties trick (which seems to be so popular) is just a special case of this. Attributes-on-properties is just a rapid way to apply certain kinds of simple validation rules, but you wouldn’t try to express more complex rules in that way, you’d just use plain C# code to throw a BusinessRuleException whenever the model layer detects a violation in the context of some operation.

  27. Ray

    I cannot seem to figure out where ValidationHelpers.RunValidationAttributes() method is from, is that some 3rd party library you used?

    Appreciate any comment on this.

  28. Alexander Gornik

    The problem with such simple validation model arises when the business logic is more complex and you need to operate with complex entities (with subentities) and even more, when you need to reuse BL pieces. i.e. save a customer as part of other, bigger business procedure. Let’s take for example a form that creates an order AND registers a new customer. In that case you have 2 options: either have the validation done in pieces (1st order, than user corrects errors, than customer). Or you can’t use exceptions for validation (at least, thrown from validated entities).
    The 1st option isn’t an option at all. For big forms with many business rules the user experience is awful in that case. Massive AJAX usage (validate on every focus change, for example) can partially improve it, but it’s hard and still has number of big issues.
    So, you really need some kind of a place to gather validation messages, etc, etc.
    Our company is currently developing a second version of our BL framework, and the central piece of it – validation is really, really hard.

  29. Steve

    @Ray – sorry if I was unclear, but this post’s code was really meant just to describe a possible approach, and isn’t something you can download and use right now. Currently you could substitute in a 3rd-party validation library such as Castle Validator to do that. Longer term, I or someone else is likely to produce a nicely-packaged validation toolkit for ASP.NET MVC, but I don’t know when.

    @Alexander – you’re absolutely right – validation can be really, really hard, because really there isn’t a division between a simple validation model and the bigger notion of business rules and procedures. All rules have to be understood in the context of some particular business process, because their meaning or rules might vary according to entity states or even just who’s logged in. The overall approach I’ve described here isn’t particularly groundbreaking – it just combines exceptions and transactions – so you can fit it into any wider business process, including processes that perform multiple actions. Maybe what you’re doing is quite similar.

  30. Superb stuff, beautifully thought out description of model validation. Got a few comments on some bits that I would be interested in your views on.

    * Presentation Model *
    For our current system we plan to use DTO’s (presentation model) as the model (rich domain hidden beneath).

    If we went for that approach we could probably avoid most of the exceptions. My thinking was that EnsureValid could return a collection of ModelValidationFailures. The controller could use this as appropriate but if it ignored it then when we try to apply those changes, in one go, to the domain then the factory/service responsible for it would do:

    if (!presentationModel.IsValid())
    throw new BusinessRuleException(presentationModel.ValidationFailures);

    * Client Side Validation*
    On client-side validation, our current plan (and it is just a plan) is to do something where in a code-generation phase we can ask the model for validation rules and then for the simple rules (not null/max length/range etc) we generate the appropriate JQuery which the front end can use.

    This would allow us to express these simple rules any way we chose, from attributes right through to my preferred option which is using specifications. Generating JQuery from specifications, I’m thinking, could work if we expressed those specifications using Expressions and found a way to convert them to JQuery. Haven’t tried but I’m sure it must be possible for simple validation.

    * Repository Validating *
    I like that a lot *but* with you may still relying on convention. For example NHibernates unit of work is going to save the Person even if you don’t call PersonRepository.SavePerson.

    Haven’t heard any good solutions to that problem though, with NHibernate people suggest interceptors (and so on) but they’re really not suitable because you want validation to be triggered by the aggregate root and what the interceptor is validating probably won’t be the root.

    Dunno a good solution to that though, other than ORM’s getting smarter about DDD.

    * Open Source *
    If you do start a project count me in, I really like your thinking on this and would be eager to get involved as I think we could make good use of some of it.

  31. Hi Steve,
    (I ask the same question to Stephen Walther)
    Steve, sorry my bad english.
    Please, you can help me?
    I develop one open source application to payment control (in brasilian portuguese) …. (snip)

  32. Steve

    @Juliano – thanks for your comment, but unfortunately I can’t debug your code for you. The MVC framework comes with full source code, so you can always inspect it to explain any behaviour that you see. Sorry I can’t give more help with that.

  33. Hi Steve, I saw you at DDD7 and really enjoyed your talk.
    Great post – I totally agree with your view. I’ve been working on ValidationAspects, an open source validation framework that follows the same principles as in your article which uses PostSharp for Interception Validation. It doesn’t do client-side validation generation yet but does provide more flexibility on registering validation functions to Models and Properties than attribute decoration alone. You can also augment and replace validation at runtime to fit changing business rules, and there’s support for exception message customization/localization. If you’re interested you can get it on codeplex.


  34. Steve

    Mike, that looks really interesting! Not sure when I’m going to get a chance to play with your code, but it’s definitely something I’d like to have a go with.

  35. Steve: I agree totally. Is this not the approach that was taken with LINQ-To-SQL Dynamic data websites (using attributes and System.ComponentModel.DataAnnotations)? I personally like that model and hope it will adopted in the next release of MVC.

  36. Steve

    @Bauma – yes, some parts of this are very close to how Dynamic Data does model validation declaratively. In this blog post I was focusing on how that can fit in cleanly with an ASP.NET MVC application.

  37. rick

    @Emad – I totally agree. Seperating the validation logic into a helper rather than implementing it upon the model is a sensible approach. The Repositor/Manager can still call this validation as steve suggests.

    Since the validation logic you suggest also implements an interface you can easily inject (using SPRING etc) different implementations of your validation logic. You could even do this conditionally. Why is this useful? Well.. different processess/workflows often require different validation..

  38. LiamV

    Really nice post, liking the idea.

    Theres one thing I can’t quite figure out though. How do you perform validation in multiple places? As soon as I throw one exception it naturally skips back and the error is caught and displayed.

    So for example, if a Username is entered that includes the correct amount of characters and correct length, it passes the validation within the model. But if another attribute in the model is invalid, an exception is thrown and the “model” error messages are displayed (which are accumulated into one IEnumerable), and the Username is deemed valid. However, it has not got to the Unique Validation which is performed in the service layer afterwards, so the Username may in fact be invalid?

    This means that a user needs to correct all the length/type “model” validation first, and is then told their Username is not unique. Is there a way around this?

    Thanks in advance!

  39. I’m coming late to this (I have your book on order so that might garner me some lee-way). I don’t know how people’s thoughts have changed on client side validation now several months later but I had some thoughts on it myself.

    I am an unobtrusive javascript fusspot if thats a term and as an developer it’s not the easiest of combinations. Anyway with your server side model attributes my temptation here would be to create helper extensions to generate inputs with classes that contain behaviour indicators. e.g. . This extension could examine the model’s attributes and output for example. It would be easy enough to use a lot of available validation plugins/libraries to build the client side validation based on the values in the class attribute.

    Again I’m coming from a strong unobtrusive angle here so I regularly use class values to describe behaviours.

  40. Whoops my examples got removed. I was just saying a htmlhelper extension like TextboxWithValClass, for example, could output an input with a class of “required range-0-99″ based on the validation attributes.

  41. Steve

    @Brian – Not sure if you’ve tried xVal, but it manages to attach validation behaviour unobtrusively (as in, with all the JavaScript in one place rather than scattered throughout the document) without even needing CSS classes to associate validation rules with elements. Pretty unobtrusive!

  42. Chris Fazeli

    I’ve seen similar approaches to validation in books and articles I’ve come across in my search to learn proper validation. I Just have a few questions about this approach.

    With respect to point [3], how are you supposed to handle a validation spectrum? Are all validations supposed to be done at the model level, or are items at the center or to the right of the spectrum (departure date must be after arrival date, username must be unique) done in the Controller? If so, doesn’t this introduce two separate validation techniques that require their own classes and code? If not, then isn’t the separation of concerns being violated?

    Also, in a somewhat unrelated point, how do you handle internationalization here? That should be a concern of the View only, but the errors and appropriate messages are located in the Model.

  43. Jason

    Where do you see security validation fitting into the spectrum? I’ve been placing it in my repositories, validating that the current user has permission to modify or create entities there rather than clogging up my entity classes. Curious to hear others’ thoughts on this.

  44. John "Z-Bo" Zabroski

    @ There’s nothing clever about this (simplicity is the goal) – when the model decides it won’t allow an operation, it throws an exception.

    Models should not throw exceptions.

    Models should respect object state machine run-to-completion semantics. Exceptions can potentially leave an object in an inconsistent state. To counteract this, some try to wrap a setter’s internal logic in a if-else-throw-Exception dialogie, and the caller in turn is required to instrument his code with a clumsy try-catch to handle it. This is a poor way to veto changes, as the exception exposes no semantics on what went wrong. Instead, the model should issue an event indicating processing of the message is “Done”.

  45. Raj Arj

    +1 to “Jacques”

    Sad, nobody else understood.

  46. Pingback: The famous Palumbo Diet!

  47. Narek

    Hi Steve,

    Thanks for your great post, it helped me a lot. There is one point I’m not sure I understand well: you mentioned that for simple validation rules, it’s a good practice to use data annotation attributes in the model, as this allows to have client side validation. But in that case won’t these attributes be checked against twice? First in the controller during model binding, and second in the model layer, in EnsureValid() method.
    Could you please clarify this point?

    Many thanks.

  48. I?ve read several just right stuff here. Definitely price bookmarking for revisiting. I wonder how a lot effort you place to make this sort of excellent informative site.

  49. I enjoy this site because a great deal utile things upon in this article: D.

  50. I can’t wait to read much more from you. This is really a great web site.