Click here to Skip to main content
15,445,997 members
Articles / Web Development / HTML
Posted 19 Oct 2005


21 bookmarked

JavaScript Validation in User Control

Rate me:
Please Sign up or sign in to vote.
2.40/5 (9 votes)
19 Oct 2005CPOL3 min read
This article shows how to implement a JavaScript block in a UserControl.


I have been searching in the internet to find ways to call JavaScript validation code from a User Control, but failed to find any. Then one of my friends helped me out in doing the task. This article will help new learners and developers who come across the scenario which I had. In our user control there is a dropdownlist dynamically loaded with data. It happens that we require to set focus on the Submit button on the change handler of the dropdown and even want to put some validation into it. Once the user changes an option in the dropdownlist and press the Enter button, it should call the Submit button event handler function. This will become clear while I take you through the example.

Key Scenario

  • Create a Web Form: Main.aspx
  • Create a User Control: UserJs.ascx

Implementation of the User Control

We can create a User Control using VS.NET 2003 by selecting a new item in the Solution Explorer project view. On creating the User Control we add the following code in the code behind. On the page load, we register the JavaScript function so as to call it from the code behind.

'Put user code to initialize the page here
'This function will check whether selected index is 0
Dim strScript1 As String = "< script language" & _
    "=JavaScript > function CodeBehindButtonJs() {"
strScript1 += "if (document.forms[0]." & uCtrlId & _
   "_ddlItem.selectedIndex == 0){alert('Validation:" & _
   "Please Select Item');return false;};}"
strScript1 += "<"
strScript1 += "/"
strScript1 += "script >"

'This function will set focus on submit
'button on dropdownlist change event.
Dim strScript2 As String = "< script language=" & _
    "JavaScript >  function CodeBehindDDlJs(me) {"
strScript2 += "document.forms[0]." & uCtrlId & "_btnSubmit.focus();}"

'Here you can achieve id's by passinf this pointer too.
strScript2 += "alert('You selected '+ me.value)}"
strScript2 += "<"
strScript2 += "/"
strScript2 += "script>"

'Register javascript block to server control event.
If (Not Page.IsStartupScriptRegistered("Startup1")) Then
    Page.RegisterStartupScript("Startup1", strScript1)
End If
If (Not Page.IsStartupScriptRegistered("Startup2")) Then
    Page.RegisterStartupScript("Startup2", strScript2)
End If

'Call javascript function on controls event
ddlItem.Attributes.Add("onchange", "return CodeBehindDDlJs(this);")
btnSubmit.Attributes.Add("onClick", "return CodeBehindButtonJs();")

If we View Source any aspx page having the User Control, we will find that the dropdownlist source will look like this:

<select name="UserJs1:ddlItem" id="UserJs1_ddlItem" 
        onchange="return CodeBehindDDlJs();" style="width:120px;" >

The dropdownlist ID in the above case is ddlItem in the User Control and "UserJs1_ddlItem" in Main.apsx. In order to trap HTML elements in the User Control we require to use document.form[0].elementId. So this element ID is to be known by the User Control. For this we define attributes in the User Control, which will be used in Main.aspx.

Public uCtrlId As String = ""

Implementation of Main.aspx

Now we create the Main.aspx. In Main.aspx drag and register the User Control. In the HTML part, include the following property as shown. This will set the value of the User Control ID and it will be retrieved in the User Control for JavaScript validation.

    <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
        <uc1:userJs id="UserJs1" runat="server" uCtrlId="UserJs1"> </uc1:userJs>
< /body>

We can see that our case was different. If we have to control any web control by itself like on a change event handler, we have to trap the selected index and then the above process won't be difficult. In such a case we have to pass the 'CodeBehindDDlJs(this)' pointer to the JavaScript function. This pointer is nothing but a pointer to the object. The case which I demonstrate is that a control action has impact on another control and in that case we are not having the ID of the other control in the User Control JavaScript. So we have to set a variable attribute to store the User Control ID. That will be document.form[0].usercontolId_ddlItem.selectedIndex. This is how things work. There might be a number of ways to achieve this. I found one and I liked to share it. Hope this will help.

Note: I tried to trap the LinkButton object using the above method but in the alert statement I always got it as 'undefined'.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Technical Lead
Australia Australia
Whatsup-->Exploring--> MVC/HTML5/Javascript & Virtualization.......!

Comments and Discussions

GeneralAnother way with jQuery Pin
imanrahmani22-May-09 18:32
Memberimanrahmani22-May-09 18:32 
Questionhow we use javascript validation of controle in user control page in .net Pin
skumars.509-May-07 23:07
Memberskumars.509-May-07 23:07 
QuestionWhat if you have two of the same type controls... Pin
ZeroDefectMachine10-Jan-07 5:07
MemberZeroDefectMachine10-Jan-07 5:07 
Questionwhy for uCtrlId?? Pin
RomaHagen6-Nov-06 5:13
MemberRomaHagen6-Nov-06 5:13 
QuestionWhat if the user control is dynamically loaded? Pin
sinanju26-Jan-06 20:31
Membersinanju26-Jan-06 20:31 
AnswerRe: What if the user control is dynamically loaded? Pin
Ricardo Casquete22-Feb-06 3:16
MemberRicardo Casquete22-Feb-06 3:16 
QuestionIsn't there another way? Pin
dwatkins@dirq.net26-Oct-05 9:29
Memberdwatkins@dirq.net26-Oct-05 9:29 
AnswerRe: Isn't there another way? Pin
RomaHagen6-Nov-06 5:21
MemberRomaHagen6-Nov-06 5:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.