MVC 3 and DRY custom validation - asp.net-mvc

Unless I'm missing something (which is very possible), it seems to me that custom validation has always violated DRY. In all the examples I've seen, even with the brand new Unobtrusive Client Validation introduced w/ MVC 3, we have to create .NET code for our server-side validation, and jQuery (or JavaScript code) for client-side validation.
I understand that there's no such thing as a .NET-to-jQuery translator that would facilitate DRY server/client validation, and I guess that would be the only way to have true DRY validation that works both server and client side.
But I would be perfectly content with having custom validation always performed on the server. The data needed to pass into custom validation (in my case) is usually limited to one or two fields, and the server-side logic is usually pretty quick, even if it has to hit the database.
Is there no OOTB mechanism for wiring up custom validation using attributes, then having your client side validation use Ajax to execute the validation server-side and respond to the client? Or, has someone come up with such a solution?
Or is it a matter of, in the end, the tradeoffs of repeating the custom validation is better than the issues introduced w/ always executing custom validation server side?
Thanks in advance.

AFAIK, there is nothing OOTB (Out Of The Box).
As for the tradeoffs - though violating DRY, you gain several things:
Immediate feedback to the user (improved usability)
No round tripping in case of validation errors (less load on server)
Of course, apart from violating DRY and opening yourself to those issue, you also end up with a larger payload to the client (extra javascript).
No one can tell you whether these tradeoffs are worth it - you need to decide what is right for your application, users and client.

OOTB: http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.98).aspx
You aren't really validating DRY here. The concept of DRY is a bit more nuanced than simple duplication of code. There are acceptable tradeoffs, especially when coupling concerns are taken into account.
When people ask this question, which is quite often if you search around, I usually refer them to the DDD concept of bounded concepts. Using [Remote] and forcing DRY when it comes to validation tends to bunch up tons of concerns in one place and merging the responsibilities of several layers. Business Logic vs. Persistence and Data Integrity Logic ( non nulls ).
#Darin Dmitrov says it pretty well in a lot of his answers he's made to this exact question. Validating that a required field is filled in is much different from making sure Sally has enough credit to make a purchase and should be treated much differently.
Client validation is best used for basic concerns and not be overloaded with more heavy operations. The impact on usability from client validation is really minimal. There is nothing "unusable" about posting a form and waiting for a refresh. It is more fluent but not anything that will make or break the success of your application.

I don't really share your concerns about violating the DRY principle in this case, but it looks like a couple other people have already discussed that.
However, your idea sounds a lot like the new remote validation feature that was added with MVC 3:
How To: Implement Remote Validation in MVC3
On the other hand, nothing is stopping you from having all of the built-in simple checks performed on the client side, and doing all of the heavy custom validation only when posting back to the server.

Related

How do deal with commas for input/display of large numbers?

I recall having to deal with this type of situation years ago and from what I can tell online, it really hasn't gotten any easier.
I have two possible scenarios. One, is where the user wants to see the number just input formatted with commas after exiting the input box. The other is where the user wants to actually enter the commas.
Both situations make validation and dealing with passing the data to the backend as a Decimal a bit more interesting. I realize this can be done through a variety of possibilities such as keyup/keydown/blur/focus events; modifying the jQuery validator with custom validation, etc. But this seems to imply a bunch of potential new functions and new places for things to go awry on different browsers. We've had tons of fun dealing with how these events, like blur/keyup react in different browsers and it can be a bit nightmarish.
Our current views use the HTML 5 . This facilitates validation and entry without a lot of coding. If possible, we'd like to keep using that type of input.
The user might also want to not be allowed to enter a decimal (for certain types of quantity inputs).
Also, the solution needs to work on both IE8 and Safari (for the iPad). Currently, we have a single view for all of our pages that happens to fit the iPad footprint.
Are there any elegant and simple solutions for dealing with this type of request?
Asp.Net MVC allows you to use jQuery unobtrusive validation which will take care of the heavy-lifting of cross-browser support for you.
You could decorate your view model property with a Remote attribute, which would then tell the browser validation scripts (again, without you having to write code) to call a controller/action for the field. Then, you create that controller/action and do your validation there (you can simple try to parse the number) and send back a message if things fail.
The reason I suggest this is simply for the reason that the remote validation is already a known, working thing and whatever you write on the server won't affect any client. You can be as fancy as you like in the validation without having to test JavaScript.
Here's an intro to remote validation - just don't be alarmed, there is a lot of text and the way the code is written makes it look more involved than it actually is.
Spin up a new project and you should have this going in under 15 minutes.
Best regards.
Edit
If you do want to go with a client-side solution, try something pre-built and community supported, such as autoNumeric.

What advantages does Mvc jquery validation offer?

What advantages, if any, does MVC jQuery Validation offer over the built-in MVC client validation?
I've used the built-in validation and am just curious as to if I'm missing anything or not.
How about customisation? I'm sure not everything is covered with the standard validators.
For example, our products are meant for people over 14yo so it's be nice to validate that client side rather than tie the server up with silly requests.
You can then share this and have a standard way of validating DOB.
MVC jQuery validation is done on the front end (client side), without submitting data to the controller (Server side). So it can save you some bandwidth/processing.
If you have a slow or overloaded server, users will get a quicker response to validation errors this way as well.
Server side validation is essential/required since it makes sure you are getting good data before you save it. The client side is nice to have, but shouldn't be all you have since its possible to bypass.

Is there any point to writing your own validation framework for MVC beta or do you expect one will be released soon?

There have been plenty of questions on MVC validation but so far the answer has been pretty much inconclusive.
For my needs in particular, I would like something that generates client validation and server validation from the same description and should allow both model based attributes as well as code based declarations for those using an ORM (e.g. LINQ TO SQL) exclusively.
I have seen some validation packs that have been whipped up to do this but they tend to introduce a lot of dependencies or are reasonably incomplete (e.g. no support for check boxes or no "higher-level" validation).
Do we begin writing our own validation framework or do we wait in hope that the team may actually release something now that they have the structure for validation in place and jQuery on board?
For those out there actually using MVC in the field now what are you using for validation?
Are you aware that validation semantics have been added in preview 5? This article from Scott Gu describes how to use it, and this one details the changes in the beta.
I have not personally used it, and it may not fit all your requirements, but I have no doubt it could be extended to behave like you want.
The best way as of the released MVC 1.0 is to use xVal.
You may also need to look at this post on implementing Linq2SQL with xVal in case that hasn't been resolved/doesn't work.

Where do you do your validation? model, controller or view

Where do you put user input validation in a web form application?
View: JavaScript client side
Controller: Server side language (C#...)
Model: Database (stored procedures or dependencies)
I think there is validation required by each level:
Did the user input a sane value
are dates actual dates, are numbers actualy numbers ...
Do all of the checks in 1. again plus checks for malicious attacks(IE XSS or SQL injection)
The checks done in 1. are mainly to avoid a server round trip when the user makes a mistake.
Since they are done on the client side in javascript, you can't trust that they were run. Validating these values again will stop some malicious attacks.
Are dependencies met (ie. did the user add a comment to a valid question)
A good interface makes these very hard to violate. If something is caught here, something went very wrong.
[inspired by this response]
I check in all tiers, but I'd like to note a validation trick that I use.
I validate in the database layer, proper constraints on your model will provide automatic data integrity validation.
This is an art that seems to be lost on most web programmers.
Validation in the model, optionally automated routines in the UI that take their hints from the model and improve the user experience.
By automated routines I mean that there shouldn't be any per-model validation code in the user interface. If you have a library of validation methods, such as RoR's (which has methods like validates_presence_of :username) the controller or view should be able to read these and apply equivalent javascript (or whatever is convenient) methods.
That means you will have to duplicate the complete validation library in the ui, or at least provide a mapping if you use a preexisting one. But once that's done you won't have to write any validation logic outside the model.
Validation can be done at all layers.
Validating the input from a web form (all strings, casting to proper types, etc) is different from validating the input from a webservice, or XML file, etc. Each has its own special cases. You can create a Validator helper class of course, thus externalising the Validation and allowing it to be shared by views.
Then you have the DAO layer validation - is there enough data in the model to persist (to meet not null constraints, etc) and so on. You can even have check constraints in the database (is status in ('N', 'A', 'S', 'D') etc).
This is interesting. For the longest time I performed all validation in the model, right above what I would consider DAL (data access layer). My models are typically pattern'ed after table data gateway with a DAL providing the abstraction and low level API.
In side the TDG I would implement the business logic and validations, such as:
Is username empty
Is username > 30 characters
If record doesn't exist, return error
As my application grew in complexity I began to realize that much of the validation could be done on the client side, using JavaScript. So I refactored most of the validation logic into JS and cleanuped up my models.
Then I realized that server side validation (not filtering/escaping -- which I consider different) should probalby be done in the server as well and only client side as icing on the cake.
So back the validation logic went, when I realized again, that there was probably a distinct difference between INPUT validation/assertion and business rules/logic.
Basically if it can be done in the client side of the application (using JS) I consider this to be INPUT validation...if it MUST be done by the model (does this record already exist, etc?) then I would consider that business logic. Whats confusing is they both protecte the integrity of the data model.
If you dont' validate the length of a username then whats to stop people from creating a single character username?
I still have not entirely decided where to put that logic next, I think it really depends on what you favour more, thin controllers, heavy models, or visa-versa...
Controllers in my case tend to be far more application centric, whereas models if crafted carefully I can often reuse in "other" projects not just internally, so I prefer keeping models light weight and controllers on the heavier side.
What forces drive you in either direction are really personal opinion, requirements, experiences, etc...
Interesting subject :)
Validation must be done in the controller - it's the only place which assures safety and response.
Validation should be done in the view - it's the point of contact and will provide the best UE and save your server extra work.
Validation will be done on the model - but only for a certain core level of checks. Databases should always reflect appropriate constraints, but it's inefficient to let this stand for real validation, nor is it always possible for a database to determine valid input with simple constraints.
All validation should happen at least one time, and this should be in the middle tier, whether it be in your value objects (in the DDD sense, not to be confused with DTO's), or through the business object of the entity itself. Client side validation can occur to enhance user experience. I tend to not do client side validation, because I can just expose all of the things that are wrong on the form at once, but that's just my personal preference The database validation can occur to insure data integrity in case you screwed up the logic in the middle tier or back ended something.
I only do it in the View and Controller, the database enforces some of that by your data types and whatnot, but I'd rather it not get that far without me catching an error.
You pretty much answered your own question though, the important thing to know is that you can never trust the view, although that's the easiest route to give feedback to the user, so you need to sanitize on at least one more level.
Hmmmm, not sure. I would have said the Controller until I read this article re: skinny Controllers, fat Models
http://blog.astrumfutura.com/archives/373-The-M-in-MVC-Why-Models-are-Misunderstood-and-Unappreciated.html
Since most of validations depends on business rules, I do the validation on the business layer as third party tool classes. There are other types of validations, such as user input, whereas it needs to be made in the controller, but you can encapsulate those validation rules in third party classes too. Really, it depends on what to validate.
The client side validations are the minor ones, just made to build a lightweight input validation, but the server side validation is required always. You never can trust in the user input ;)
.NET have nice controls to build validations, but the business layer always needs a better approach to validate the data and those controls are not enough to that task.
Simple input validation in the view. Full validation in the model. Reason? If you change your view technology, and the validation is in the view/controller, you have to rewrite your validation for the new view. This can introduce bugs. Put it in the model, and this is reused by all views...
But, as I said, simple validation in the view for speed and ease.

Which validation library for ASP.NET MVC?

I'm trying to decide what validation approach to take for a new ASP.NET MVC project. (And wow there are plenty of options!)
The project uses NHibernate, so the first thing I considered was the NHibernate Validator (Because of tight integration with NHibernate). However, as far as I can see there are only a couple of benefits to this tight integration:
1) DB Schemas generated by NHibernate will include details of validation (e.g. column lengths will be set to max value allowed in validation). (This is not really of interest to me though, as I generate schemas manually.)
2) NHibernate will throw an exception if you try to save data that doesn't meet the validation specs. (This seems fairly redundant to me, since the data presumably will already be validated by whatever mechanism you choose before saving anyway)
If there are more benefits to NHibernate Validator please let me know!
Other libraries which I've been reading a little about include:
MS DataAnnotations
Castle Validator
Something else?
I've also been thinking about using xVal to provide client side validation from the same set of rules. However, I hear that ASP.NET MVC v2 will include something similar to xVal (integration with jquery) out of the box? Will this new included functionality render some of the others redundant?
So, I'm basically asking for people's advice on which direction to take here. I don't want to implement a particular scheme, only to have to rip it out when another one becomes the dominant tech.
What has worked for you? Which option do you think has/will have the edge?
Thanks!
I have been using FluentValidation along with jQuery validation plugin and still cannot find a situation they cannot handle.
I like xVal.
You can implement very easily client and server validation with it. Also there is support for column (property) validation on entities that you would like to use.
DataAnnotations implemented by buddy classes and JQuery client validation
Make sure you're using MVC Preview 2
You might be interested in this delegate approach. I was because i didn't like the xVal idea (the solution im currently going with) and the fact that it didn't seem to cater for complex validation cases that crossed multiple properties of the same or even different class structures.

Resources