Get ValidationSummary Error Text from Code Behind

4.2k views Asked by At

and thank you for reading this!

I may be looking right past the answer for this, or it may be that it was never designed to happen since ValidationSummary is client-side logic, but is there any way to retrieve the error text of a validation summary field in ASP.NET from the C# code-behind? The goal here is to construct a message that includes various information entered by the user, plus any errors that might be preventing that user from completing an operation.

It's fine if it can't be done since I am not expecting client side validation to be much of an issue for users in this program, but it would be nice to include for the sake of completion. Any advice would be appreciated.

Thank you!

2

There are 2 answers

1
Kirk On

Your trouble is probably that these often validate on the client side and not the server side, if they don't actually cause postback. You may be best trying to switch to a CustomValidator and do your checks there.

These happen on the server side and not the client side.

Take a look at the documentation on MSDN http://msdn.microsoft.com/en-us/library/9eee01cx(v=vs.85).aspx

I've never tried this, but here is a quick example of what may work.

Front end

<asp:TextBox id="Text1" runat="server" />

<asp:CustomValidator id="CustomValidator1" runat="server"
           OnServerValidate="CustomValidator1_ServerValidate"
           Display="Static"
           ErrorMessage="My default message."/>

Back End

protected void ServerValidation (object source, ServerValidateEventArgs args)
{
    // default to valid
    args.IsValid = true;
    int i;
    if (int.TryParse(Text1.Text.Trim(), out i) == false)
    {
        // validation failed, flag invalid
        args.IsValid = false;
        CustomValidator1.ErrorMessage = "The value " + Text1.Text.Trim() + " is not a valid integer";
    }
}
0
Eric On
  protected string GetErrors()
    {
        string Errors = "";
        bool isValidTest = false;
        Validate("myValidationGroup");
        isValidTest = IsValid;
        if (!isValidTest)
        {
            foreach (BaseValidator ctrl in this.Validators)
            {
                if (!ctrl.IsValid && ctrl.ValidationGroup == "myValidationGroup")
                {
                    Errors += ctrl.ErrorMessage + "\n";
                }
            }

        }

        return Errors.Trim();
    }