6

I am doing something like below on a web forms application;

protected void button_transfer_search_Click(object sender, EventArgs e) {

    Page.Validate("val1");

    if (!Page.IsValid && int.Parse(txtArrivalDateTrf.Text) + 5 < 10) {
        return;
    }

also, I have following code on my aspx file;

<div class="search-engine-validation-summary">
    <asp:ValidationSummary ValidationGroup="transfer" runat="server" ShowMessageBox="false" />
</div>

my question is how to add an error message to the page before return so that validation summary can grab that and displays it. I know we can do this in mvc easily but I haven't figured out how to do that in web forms. thanks !

tugberk
  • 57,477
  • 67
  • 243
  • 335
  • By "before return", do you mean on the client before the form is submitted? – IrishChieftain May 06 '11 at 13:22
  • 1
    found the answer here : http://stackoverflow.com/questions/777889/on-postback-how-can-i-add-a-error-message-to-validation-summary nearly the exact duplicate :S well, it sucks :S – tugberk May 06 '11 at 13:29
  • I voted my own question to close :S still need 4 votes guys. help me out here. – tugberk May 06 '11 at 13:30

1 Answers1

9

Whenever I find this situation this is what I do:

var val = new CustomValidator()
{
   ErrorMessage = "This is my error message.",
   Display = ValidatorDisplay.None,
   IsValid = false,
   ValidationGroup = vGroup
};
val.ServerValidate += (object source, ServerValidateEventArgs args) => 
   { args.IsValid = false; };
Page.Validators.Add(val);

And in my ASPX code I have a ValidationSummary control with a ValidationGroup set to the same value as vGroup.

Then, after I have loaded as many CustomValidators (or any other kind of validators) by codebehind as I want I simply call

Page.Validate()
if (Page.IsValid)
{
    //... set your valid code here
}

The call to Page.Validate() calls the lambda-linked method of all code-behind inserted validators and if any returns false the page is invalid and returned with no code executed. Otherwise, the page returns a valid value, and executes the valid code.

Isaac Llopis
  • 432
  • 5
  • 12