Click here to Skip to main content
11,712,524 members (69,370 online)
Click here to Skip to main content

JavaScript Validation in User Control

, 19 Oct 2005 CPOL 98.9K 633 21
Rate this:
Please Sign up or sign in to vote.
This article shows how to implement a JavaScript block in a UserControl.

Introduction

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
'<summary>
'This function will check whether selected index is 0
'</summary>
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 >"

'<summary>
'This function will set focus on submit 
'button on dropdownlist change event.
'</summary>
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>"

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

'<summary>
'Call javascript function on controls event
'</summary>
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>
    </form>
< /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'.

License

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

Share

About the Author

santosh poojari
Technical Lead
India India
Whatsup-->Exploring--> MVC/HTML5/Javascript & Virtualization.......!
www.santoshpoojari.blogspot.com

You may also be interested in...

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
drkwtkns26-Oct-05 9:29
memberdrkwtkns26-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    Rant Rant    Admin Admin   

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 19 Oct 2005
Article Copyright 2005 by santosh poojari
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid