Custom validatior in ASP.net
I'm working on 开发者_Python百科an ASP.NET/C# app.
I have 2 text boxes and I need to validate if the input text for both of them are not both null ex:
if(string.IsNullOrEmpty(TextBox1.Text) && string.IsNullOrEmpty(TextBox2.Text) )
//FAIL!!!
else
// OK!
that is, at least one txtBox has values
I was planning on using a custom validator but it seems that the validation function only gets called when something is written on the textBox i'm using has the 'control to validate'. Now, that doesn't work for me since I want to show an error message when both text boxes are empty. Is there a way to make the validation function to be called with, for example a postback? Or is there any other better approach to this case than the custom validator?
tks
If you set the 'ControlToValidate', then the validator will not fire if that control is empty. However, for a CustomValidator you can leave that empty so it will always fire.
Because the built-in validators only analyze the state of their own controls, you are forced to go with a CustomValidator for this functionality. I don't know of any better approach that still uses ASP.NET server-side validators. As Hans said, be sure to leave ControlToValidate empty, and then do the validation as in your code sample.
精彩评论