Custom Validator Not Firing (No error message, but no validation)
I have a custom validator:
<asp:CustomValidator ID="QuestionValidator" runat="server" ErrorMessage="Please select an option" ClientValidationFunction="QuestionValidator_ServerValidate" OnServerValidate="QuestionValidator_ServerValidate" ValidateEmptyText="true"></asp:CustomValidator>
I have a list of questions provided by a datalist, which I need to ensure a user selects an answer to each question. I then have my validation functions:
Protected Sub QuestionValidator_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
Dim SelectedItem As Boolean = False
For Each c As Control In Page.Master.FindControl("form1").Controls
If TypeOf c Is RadioButton Then
Dim rb As RadioButton = DirectCast(c, RadioButton)
If rb.GroupName = "AnswerOptions" AndAlso rb.Checked = True Then
SelectedItem = True
End If
End开发者_StackOverflow社区 If
Next
args.IsValid = SelectedItem
End Sub
<script type="text/javascript" language="javascript">
function QuestionValidator_ServerValidate() {
return true;
}
</script>
When I run the page, there is no validation and no error message. Please can you point out where I am going wrong, I'm suspicious it is at Page.Master.FindControl("form1").Controls
.
I have previously done such validation by looping through controls via form1.controls but this is unavailable as the page uses a form passed down via the master page.
There could be a flaw in your code. Because as per the logic if out of 50 radio buttons on your page even if just one is selected your validation will pass. Also the groupname for all the RBs is same for each item. Not sure if ASP.NET renames those and if not then all RBs with be grouped into one for all the questions.
For the looping part you can loop through DataList.Items collection instead of looping through all controls on the form: Dim item As DataListItem
For Each item In DataList1.Items
Dim ctrl As Control
For Each ctrl In item.Controls
'do your rb state check here
Next ctrl
Next item
I would try looping through either "Page.NamingContainer" or "Page.Controls" and see how that goes.
Maybe I missed something, but shouldn't You also set property ControlToValidate="ID_of_the_control_to_validate" in the custom validator?
I think you need to give ValidationGroup for the CustomValidator and all the Controls Involved in the Validaiton process
精彩评论