The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN.

The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works perfectly, except for the first time the Submit button is clicked.

The CheckBoxList is populated dynamically in the VB code behind, while the ASCX side remains simple. However, upon clicking the submit button for the first time, the ClientValidationFunction does not fire. Subsequent clicks work fine.

Below is the content of my ASCX:

<%@ Control Language="vb"
    Inherits="MyCustom.Modules.WebApps.WebAppsFormBuilderControls.WebAppsFormBuilder_Controls_CustomCheckboxList"
    CodeFile="WebAppsFormBuilder_Controls_CustomCheckboxList.ascx.vb"
    AutoEventWireup="false" Explicit="True" %>

<script type="text/javascript">
    function ValidateCheckboxList(source, args) {
        //window.alert('starting');

        var chkListModules = document.getElementById('<%= cbValue.ClientID %>');
        var chkListinputs = chkListModules.getElementsByTagName("input");

        for (var i = 0; i < chkListinputs.length; i++) {
            if (chkListinputs[i].checked) {
                args.IsValid = true;
            }
        }
        args.IsValid = false;

        //window.alert('IsValid = ' + args.IsValid);
    }
</script>

<myCustom:CheckBoxList ID="cbValue" runat="server" />
<asp:Literal ID="Literal1" runat="server">
    &nbsp;<font color="red" bold="true">*</font>&nbsp;
</asp:Literal>
<asp:CustomValidator runat="server"
    ForeColor="Red" ID="cvCheckBoxList"
    ClientValidationFunction="ValidateCheckboxList"
    ErrorMessage="At least one item must be selected." />

VB code for the user control:

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports MyCustom.Modules

Namespace MyCustom.Controls

    Public Class CheckBoxList
        Inherits System.Web.UI.WebControls.CheckBoxList

        Private _GlobalID As Integer

        Public Property GlobalID() As Integer
            Get
                Return _GlobalID
            End Get
            Set(ByVal value As Integer)
                _GlobalID = value
            End Set
        End Property

        Private Sub CheckBoxList_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

            Dim User As MyCustom.Modules.Users.UserInfo = HttpContext.Current.Items("LoggedInUser")
            If User Is Nothing Then
                Dim objUserInfo As UserInfo = UserController.GetCurrentUserInfo
                Dim UserID As Integer = objUserInfo.UserID
                If UserID > -1 Then
                    If HttpContext.Current.Items("LoggedInMyCustomUser") Is Nothing Then
                        Dim myCustomUserController As New MyCustom.Modules.Users.UserController
                        User = myCustomUserController.MyCustomGetUser(6, UserID, True)
                        HttpContext.Current.Items("LoggedInMyCustomUser") = User
                    Else
                        User = HttpContext.Current.Items("LoggedInMyCustomUser")
                    End If

                End If
            End If

            If User Is Nothing Then Exit Sub
            Dim MyCache As New GlobalTextCache(User.CorpID)

            For Each li As ListItem In Me.Items

                Dim NewVal As String
                NewVal = MyCache.GetGlobalText(li.Text, User.PreferredLocale, User.CorpID)

                If NewVal IsNot Nothing AndAlso _
                    NewVal <> "" Then
                    li.Text = NewVal
                End If
            Next
        End Sub
    End Class
End Namespace

Any insights?

Answer №1

There seems to be a glitch in my setup causing some issues. As a result, I've opted for Server Side validation over Client Side validation.

To implement this, simply add the OnServerValidate property to the CustomValidator:

<asp:CustomValidator runat="server" ForeColor="Red" ID="cvCheckBoxList"  OnServerValidate="cvCheckBoxList_ServerValidate" ErrorMessage="At least one item must be selected." />

Then, create the function on the custom control (assuming cbValue is a CheckBoxList control):

Protected Sub cvCheckBoxList_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvCheckBoxList.ServerValidate
    Dim isValid = False

    For Each c As ListItem In cbValue.Items
        If c.Selected Then
            isValid = True
        End If
    Next

    args.IsValid = isValid
End Sub

I came across this Server Side solution here, on stackoverflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display an input field in VueJS with a default value set

Dealing with a form containing various editable fields, I devised a solution. By incorporating a button, clicking it would conceal the label and button itself, while revealing a text box alongside a save button. The challenge lays in pre-filling the textbo ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

Tips for Sending Emails from an Ionic Application without Utilizing the Email Composer Plugin

I am attempting to send an email from my Ionic app by making an Ajax call to my PHP code that is hosted on my server. Below is the code for the Ajax call: $scope.forget = function(){ $http({ method: 'POST', url: 's ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

What is the best way to organize these checkboxes using BootstrapVue's layout and grid system?

My BootstrapVue table setup looks like this: https://i.sstatic.net/K3Rwy.png This is the code for the table: window.onload = () => { new Vue({ el: '#app', computed: { visibleFields() { return this.fields.filter(field ...

Visuals derived from JSON information

Here is the JSON data retrieved from a web API: [{"FileName":"D:\\StuckUpTask\\Insta\\Insta\\Images\\/download (1).jpg"},{"FileName":"D:\\StuckUpTask\\Insta\\Insta\&bsol ...

How can Selenium in Python be used to click a JavaScript button?

I need help automating the click of a button on a webpage using selenium Here is the HTML for the button: <div class="wdpv_vote_up "> <input value="7787" type="hidden"> <input class="wdpv_blog_id" value="1" type="hidden"> </div& ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...

Simple JavaScript timer with loop and pause

Having trouble with a countdown script and encountering multiple issues. The script does not run smoothly Difficult to make it repeat (closure) Struggling with delaying the start and repeat (closure) Seeking assistance in fixing this code which should i ...

Display JSON information in GridView using ASP.NET

Could anyone assist me with a json data issue I'm facing while populating a gridview? Everything works fine when the headers part is excluded from the json data, but once it's included, an error occurs. Any help would be greatly appreciated as I& ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...

Read a local file using the HTML5 FileReader

I am currently working on developing an offline application that can read text from a locally stored text file. I have been researching and found that using html5 and FileReader can make this possible. My goal is to set a hard-coded relative path for the ...

I am experiencing an issue wherein after using jquery's hover() function, the CSS :hover state is not

Following the jquery hover function, the css hover feature ceases to work. In my html, there are multiple svg elements. A jquery script is applied where hovering over a button at the bottom triggers all svg elements to change color to yellow (#b8aa85). S ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...