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 !

3
  • By "before return", do you mean on the client before the form is submitted? Commented May 6, 2011 at 13:22
  • 1
    found the answer here : stackoverflow.com/questions/777889/… nearly the exact duplicate :S well, it sucks :S Commented May 6, 2011 at 13:29
  • I voted my own question to close :S still need 4 votes guys. help me out here. Commented May 6, 2011 at 13:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.