views:

22

answers:

1

I am wondering what the prefered method of validating user input in asp.net using an existing method call is. I have implemented this a couple of ways now and while they all work I get the sense that there might be a better or "optimal" method?

I have an asp.net textbox

<asp:TextBox ID="myTextBox" runat="server" />

I also have a couple existing methods available to me on the objec that the form will eventually populate and save

public static bool IsNameValid()
public bool IsValid()

I'm wondering how people would wire up those items to a validation control (I'm assuming customValidator?). I'd like to avoid rewriting the validation in JavaScript (to avoid duplication of code).

+1  A: 

Use a CustomValidator, and set the EnableClientScript property to false, forcing it to go to the server for validation. Then in the custom validator's ServerValidate method, set the args.IsValid property to the result of your methods above.

The advantage to using the validator is that when you go to your "submission" method for the form, you can wrap the final processing logic around a If Page.IsValid() block, which will make sure all validators come back as true before processing.

Dillie-O
so you do have to wrap your submission click in an if statement then? is there any method of doing this that you don't have to do that?
ChrisHDog
Not really. Even if you have validators on the page, a page submission will still occur whether or not they come back as valid or not. Typically the validators will trigger on their own, especially if the client side scripts are generated, and simply set their state to true or false depending on if they are valid or not. It is up to you to determine whether or not to process the validator data.
Dillie-O
thanks Dillie-O, that is great information - very helpful
ChrisHDog