Robert
Robert

Reputation: 1159

How do you determine which validator failed?

I am working with a page and I am getting an Page.IsValid = false and I am trying to determine which control is causing the validation problem.

Upvotes: 38

Views: 19512

Answers (4)

NYCdotNet
NYCdotNet

Reputation: 4647

The accepted answer allows you to find the validation message of the validator that failed. If you want to find the ID of the control that failed validation, it is possible to get that by casting the validator to a BaseValidator which exposes the ControlToValidate property. For example:

For Each v As BaseValidator In Page.Validators
    If Not v.IsValid Then
        ' You can see the control to validate name and error message here.
        Debug.WriteLine(v.ControlToValidate)
        Debug.WriteLine(v.ErrorMessage)
    End If
Next

Upvotes: 8

Ozziereturnz
Ozziereturnz

Reputation: 488

Credit to Steven for this answer, but I had to make some changes for it to work as this.Validators.Where() had some problems.

using System.Linq;

List<IValidator> errored = this.Validators.Cast<IValidator>().Where(v => !v.IsValid).ToList();

Upvotes: 29

Nitin
Nitin

Reputation: 41

To check which Validator is being fired, just check the HTML in Firebug and if any Validator is not having display:none; property or is having visibility:visible in its properties then it is the one which is causing Page.IsValid false.

Upvotes: 2

Chains
Chains

Reputation: 13157

In code (page_load), you can do this:
(per MSDN: http://msdn.microsoft.com/en-US/library/dh9ad08f%28v=VS.80%29.aspx)

If (Me.IsPostBack) Then
    Me.Validate()
    If (Not Me.IsValid) Then
        Dim msg As String
        ' Loop through all validation controls to see which 
        ' generated the error(s).
        Dim oValidator As IValidator
        For Each oValidator In Validators
            If oValidator.IsValid = False Then
                msg = msg & "<br />" & oValidator.ErrorMessage
            End If
        Next
        Label1.Text = msg
    End If
End If

In the markup, you can...

  • You can put "text" on your validator (like an asterisk...)
  • Or use a validation_summary control (which requires an error message on your validator)...

Upvotes: 25

Related Questions