views:

199

answers:

4

I want to have client-side validation for quick response to the user without a roundtrip to the server.

I also want the same validation for securing the code behind action on the business and data access layer.

How do you reuse that kind of code pragmatically in ASP.NET?

(note: ASP.NET, C# 3.0, .NET 3.5, Visual Studio 2008)

A: 

For the UI:

You can call the method/property Page.IsValid and then, if it returns false, inspect the validators and print their error strings manually. Or just do your own error handling, whatever you see fit.

ie:

    protected void OnSomeEvent(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            ErrorMessage.Text = "your socks are the wrong colour";
            return;
        }
        // Continue processing.
    }

Assuming a simple literal for showing an error. Obviously tailor to your own needs.

Simon
And how about the reuse of the validation code in the business and data layer ?
Patrick Peters
I've never re-used the code for an ASP.NET validator in an ADO.NET layer so don't know. Hence why my answer was scoped purely to the UI. The code shows how to check that the validators are ok in the code behind. You can, if the validation step fails, iterate over them for the specifics of each.
Simon
The UI validation is the one that can be found on MSDN. Reuse of code in the BL and DL is more challenging... so I am waiting for a better answer though...
Patrick Peters
That's fair enough. Required field validators (etc) are all easy to implement. However, not many people run the same checks in the codebehind. I mis-read your question to include that. As in 'from the code that collects the post data all the way to the database'. Sorry it wasn't so useful!
Simon
A: 

Build a validation project give it a web service interface so you can call with ajax, here is a tutorial, and then add it to your biz layer and your Dal layer. then all of your code can use the same validation code.

Bob The Janitor
A: 

A friendly warning not to expect too much success for your efforts. This article describes quite well the fallacies in thinking about the mythical "business layer" that you are seeing in your efforts to centralize and avoid duplication of code. The upshot is that doing the kind of unification you're talking about is often too difficult to justify.

Jeff Kotula
+1  A: 

I don't know if there is something for regular asp.net, but you might want to check how this open source project is going about it: http://xval.codeplex.com/. Note, I haven't really used it, so I am not sure how good it is.

eglasius