RequiredFieldValidator control not working after adding JavaScript to Button Click Event

I'm trying to add a JavaScript function to prevent submitting a page with an empty textbox when a specific drop down list category is selected. The function triggers on the Submit button onclick event.

However, upon adding the code, the existing RequiredFieldValidators for the other textboxes no longer checks for required fields when the Submit button is clicked.

Can anyone figure why this is happening and how I should best accomplish a way to prevent submitting a page with an empty textbox when a specific drop down list category is selected. Appreciate any advice I can get.

Here is the JavaScript function I'm using:

private void Page_Load(object sender, System.EventArgs e)
            if ( !IsPostBack )    // FIRST TIME
                imgSubmit.Attributes.Add("onclick","return XstreetValidTR();");

                    function XstreetValidTR()
                        var pointer  = document.forms['Search']._ctl1_dblTroubleTicketType;
                        var pointer1 = document.forms['Search']._ctl1_txtCrossStreet;
                        var pointer2 = document.forms['Search']._ctl1_imgSubmit;

                        // figure out if cause requires x-street
                        if ( pointer.options[pointer.selectedIndex].value.charAt(pointer.options[pointer.selectedIndex].value.length - 1).toString() == '1' && (pointer1.value == '' || pointer1.value.length == 0) )
                            alert('For this type of Cause, you must enter a Cross Street');
                            return false;

                        Submitted = true;
                        return true;


2/12/2008 12:02:29 AM 24353 articles. 2 followers. Follow

6 Replies

Similar Articles

[PageSpeed] 35
Get it on Google Play
Get it on Apple App Store

instead of using java script,you can use compare validator for performing this function

(If this post is helpful, please mark as an answer )


Web Developer
ipix solutions
My Blog:Prajeesh's Tech blog
My company :IPIX Solutions
2/12/2008 7:46:42 AM

I thought about using a compare validator control, but however, it does not have the ability to require a field in another textbox based on the comparison criterion. Are there any other alternatives?  



instead of using java script,you can use compare validator for performing this function

2/12/2008 11:43:44 PM

Hi Check this code out .. this might help

 <!--   Code start -->

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorTest.aspx.cs" Inherits="ValidatorTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        function ClientValidate(source, arguments)
            var LstBox = document.getElementById("<%=LstItems.ClientID%>");
            var TxtBox1 = document.getElementById("<%=TxtBox1.ClientID%>");
            if (LstBox.value == "1" && TxtBox1.value == "")
                 arguments.IsValid = false;
            arguments.IsValid = true;
    <form id="form1" runat="server">
    <asp:Label ID="LblMsg" runat="server"></asp:Label>
    <br /><br />
    <asp:DropDownList ID="LstItems" runat="server">
        <asp:ListItem Value="1">--One--</asp:ListItem>
        <asp:ListItem Value="2">--Two--</asp:ListItem>
        <asp:ListItem Value="3">--Three--</asp:ListItem>
        <asp:ListItem Value="4">--Four--</asp:ListItem>
    <br /><br />
    <asp:TextBox ID="TxtBox1" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CvTxtBox1" runat="server" ClientValidationFunction="ClientValidate" ErrorMessage="For One You Must Enter a Value." Display="dynamic"  EnableClientScript="true"></asp:CustomValidator>
    <br /><br />
    <asp:TextBox ID="TxtBox2" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RfvTxtBox2" runat="server" ControlToValidate="TxtBox2" Display="Dynamic" ErrorMessage="Required"></asp:RequiredFieldValidator>
    <br /><br />
    <asp:Button ID="BtnSubmit" Text=" Submit " runat="server" OnClick="BtnSubmit_Click" />

[Please mark the post as answer that helps you.]

Farhan Uddin Khan
Enpointe Technologies
2/13/2008 1:51:02 AM

In your javascript function

add this peice of code

Page_ClientValidate('ValidationGroup Name')

try this

2/13/2008 1:44:07 PM

 Thanks for everyones help. I used FarhanK's solution to call the JavaScript using a customvalidator control. Here's another site with a nice reference:


2/22/2008 9:56:16 PM


you can use the below even with out using the custom validator....

<asp:Button id="" .... OnClientClick="if(Page_ClientValidate()) {here call your Js function...} else {return false;}"  />

Software Engineer.
2/23/2008 5:21:03 AM

Similar Artilces:

How to access Client Side control in server side button click event?
Hi all, I need to access client side control from server side code. For an example <form id="form1" runat="server"> <table> <tr> <td>UserName:</td> <td><input type="text" id="textBoxUserName" /></td> <td><asp:Button ID="buttonShow" runat="server" Text="show" OnClick="buttonShow_Click" /></td> </tr> </table>   </form> I need to access the textBoxUsername in the server side button click event. How to do that? Than...

Adding events to controls, e.g. adding a click event to a label control
 Hi, Is it possible to add a click event to a label control so that one can make something happen when a user clicks the label? How can it be done? One could of course use a linkbutton control, which has an in-built click event. Unfortunately a linkbutton insists on doing a postback every time it is clicked.Thank you!Regards.   Label is span control in html call javascript onclick event <span id="fkdsjfl" onclick=" ">here</span> if you want to call postback event then chk it If this post...

ISSUE WITH Control's behaviour inisde UPDATE PANEL
 hii evry1..,             i have an strange chk it out..                      aspx page:            < asp:UpdatePanel ID="OUpdatePanel" runat="server" >                <ContentTemplate>             &nbs...

Adding a javascript button click event to create user button
Hi:  I have a screen to create a username. In the create user screen i ahve put my terms and conditions for the site. In order to create a username the user has to accept the terms and conditions, for that he needs to check the checkbox accepting the terms and conditions. My question is:     Where do i add the javascript(client side) button click event in order to chck whether the user has checked the checkbox or not. If he did not check the checkbox and username should not be created.Can anybody please help with this!Thanks....

Calling Button Click Event From Another Event With Client Side Code
Hi All,I am trying to call a (server control) button's click event from another event where the button has a client side code as well. I defined my button as: <asp:Button runat="server" id="button1" onclick="button1_Click" onclientclick="someJSFunction(); return false;" text="..." />  The button1_Click event does not contain any server side code, I just need a reference for my other event to call to, like so: void OtherEvent(object sender, EventArgs e) { button1_Click(sender, e);}  What happens is that button1_Click is being fired but the client side code ...

Firing both Client side event and server side event for server side button
I am having some difficulties getting this to work.. I have button_click ( and ClientClick (Javascript).  Javascript is firing fine.  Server script is not. may be you have return return false in the in the javascript which is why its not firing server side event.You should add javascript evelt like thisbutton1.onclientclick = "functionname" Function should nopt return false. Vikram www.vikramlakhotia.comPlease mark the answer if it helped you...

how to bind Javascript Confirm ok event with server side button click event
Hello I ve a popup menu to "add a group" or "Delete Group" when i click "Delete Group" menu i want one Javascript confirm box which will ask permission whether to delete or not. When user will press "Ok" on confirm box, i want to call one server side button_click event? How should i proceed with this? Hi dee1j,When you are in your javascript at this point:if (confirm('Do you want to delete')){   var myButton = document.getElementById('IdOfButtonIWantToClickWhenConfirmIsOk');;} Please gi...

executing server side code and client side (javascript) code simultaneously while clicking a button
how to execute server side code and client side (javascript) code simultaneously while clicking a button in You can't. When clicking a button: the client-side executes, the page does a PostBack, then the server-side executes.NC... what if i want to update a database and then open a new windows is it possible with

can picturebutton or button control use Client-Side Events and Default Event Handlers
hello all: can picturebutton or button control use Client-Side Events and Default Event Handlers? we can use Web DataWindow client-side events . How about picturebutton or button control else? for example #if defined PBWEBFORM then pb_2.JavaScriptFile = "CRM.js" pb_2.OnClicked = "PBPictureManager_delete" #else /*action*/ #end if pb_1 is picturebutton ,but complier is error. So ,How we can ? Pls thanks I don't think you can add client-side events to those controls. You can code these events if you create a button or picture button on a ...

Web User Control - Button Click
I have a web user control which is has one Button control on it. It has a event for handling the click... if I put this user control ( button ) at the top  of the page, the click event does not get fired just page is refreshed...but where as if I move to the bottom of the page, ButtonClick is fired ???? I am completely clueless why is this change of behavior with respect to the position of the control?? Thanks. could you show us the code that you have problem with ...   Here is the code ( i have taken out the unwanted part of the page ) Please note that the bSave does ...

Hi,    I am working in With ajax extension. In a form have a update button,on the first click,event not calling,on the second click its calling that event successfully. Give a solution for this problem. Thanks in Advance Are you using updatepanels? There might be a problem with the lifecycle of your page. Can you show some code?Jef Claes~~~~~~~~~~Visit my blog S ur thought is right i am using update panel.My Code is below    </script> <br /> <br /> <asp:Label ID="Label1" runat="server" CssClass="header...

Adding JavaScript function to button click event
I am new to JavaScript. I have a separate js file with the following two functions:function CartConfirmDelete(){  var result = confirm('Do you really want to delete the checked items in your shopping cart?');  if (result)    {      return true;    }  else    {      return false;    }}  function CartConfirmEmpty(){  var result = confirm('Do you really want to empty the contents of your shopping cart?');  if (result)    {&nbs...

How could add a javascript function to a button click event as a part of its click event handler?
Hi, The title might be confusing. What I want is simply two pages, Page1 and Page2, when I click on a linkbutton on page1, page2 pops up. I used to use a little bit of javascript to do this, and it worked just fine. I just added the following line of code to the Page_Load event of Page1:   protected void Page_Load(object sender, EventArgs e) { LinkButton1.Attributs.Add("onclick","'Page2.aspx',null,'height=500,width=650,status=no,resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no')"); } But now, I have...

How do I fire a server side button click event from javascript?
here is my server side event.plz can any one help me how to call this function using javascript.   protected void update_week(object sender, EventArgs e) {DataSet month_dataset = (DataSet)Session["month_dataset"]; LinkButton b = (LinkButton)sender;int week = Convert.ToInt16(b.Text.Substring(4,1)); GridView2.Visible = true;GridView3.Visible = true;ETA_funtions.etaclass obj = new ETA_funtions.etaclass(); weeknum = week; Hashtable hshtable = obj.get_strt_end_dates(weeknum, Convert.ToDateTime(monthlbl.Text));TimeSheet.wkenddt = (int)hshtable["wkenda...

Web resources about - RequiredFieldValidator control not working after adding JavaScript to Button Click Event -

Artist Archive
Artist,Archive,Organization,Artwork Home Search Periodical Search Events New Artist Art Finder FAQ My Center Email RequiredFieldValidator Password ...

DaniWeb Solved Articles - Technology Publication Meets Social Media
An online discussion community of IT professionals. Forums to get free computer help and support. We are a social technology publication covering ...

Base Compare Validation Control Properties
Developer Network Get tools MSDN subscriptions Sign in Opportunity iOS Android Web .Net Design Games Platform Tablet & PC Phone Cloud Connect ...

Search Center - Info
Select a Language English English (India) Chinese (中文) French (Français) German (Deutsch) Italian (Italiano) Japanese (日本語) Korean (한국어) Polish ...

localflux - Privacy
The celebration of difference

Mason City, Iowa - Official Website
Calendar - Jobs - E-Notices - Staff Directory - Contact Us Blue Zones Projectâ„¢ City Mission Statement Community Profile Our History Press Room ...

Feedback * *
Send feedback to IRIN Comment is required Email address * RequiredFieldValidator Invaled email address Your Name Letters * Required field Generate ...

Rockingham County, North Carolina - Official Website
Site Map - E-Notify - Staff Directory - Contact Us Document Center Governmental Directory 2011 Landfill (Solid Waste Disposal) Online Services ...

RequiredFieldValidator Control
Use the RequiredFieldValidator control to make an input control a mandatory field. The input control fails validation if the value it contains ...

localflux - Post
the innovative design of mobile 'walking' city structures. a viable future urban design concept?

Resources last updated: 12/15/2015 10:14:23 AM