1

I am using RegularExpressionValidator to validate a textbox.

Now if the textbox is valid,i need to display a "Page is Valid" message on Label Control.

Do I do it in Code Behind or do i declare the label in javascript itself?

In javascript I have tried using the :

document.getElementById("LabelId").innerText="Your Text Here"

but it shows Microsoft JScript runtime error:

Unable to set value of the property 'innerText': object is null or undefined".

Also I have tried using innerHTML instead,but it shows the similar error. So whats the correct way to assign value to label? Edited: Below is my aspx coding:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"        
CodeBehind="RegularExpressionValidator.aspx.cs" Inherits="ValidationTask.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Label ID="LabelText" runat="server" Text="Label"></asp:Label><br />
<script type="text/javascript" language="javascript">
   function ValidatePage() {
       debugger;
       if (Page_IsValid) {
           document.getElementById('<%= LabelText.ClientID %>').innerHTML = 'Page Is Valid';
       }
       else {
           document.getElementById('<%= LabelText.ClientID %>').innerHTML = 'Page is Invalid';
       }
   } 
</script>  
<asp:Label ID="LabelZip" runat="server" Text="Enter Zip Code"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Enter" OnClientClick="return ValidatePage()"  />

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" 
ValidationExpression="\d{5}" runat="server" ErrorMessage="The zip code must be 5 numeric   
digits"></asp:RegularExpressionValidator>
</asp:Content>

Thanks in Advance.

P.S. I am new here and this is my first question. Please ignore if i have made any mistakes.

Khan
  • 344
  • 1
  • 7
  • 21
  • Try adding your code on document load or ready. Object undefined or null occurs when the element is not found in dom. refer http://stackoverflow.com/questions/4488714/change-label-text-using-javascript – Harshada Chavan Jan 21 '14 at 05:06
  • try to use client id of label.... like `"<%=LabelId.clientID%>"` or using inspect element – The Hungry Dictator Jan 21 '14 at 05:23
  • Can you inspect the element and make sure you have the right id? – Esteban Araya Jan 21 '14 at 05:25
  • are u using a master page ?? – iJade Jan 21 '14 at 05:35
  • @HarshadaChavan Thank you. I have referred the link which you posted, And have implmented the same. There isn't any error but the value of label is not being displayed. – Khan Jan 21 '14 at 06:26
  • @RonakBhatt Yes I have implemented this but still not able to get the text to the label. Also I am fairly new to javascript and dont really understand the the term "using inspect element". Thanks. – Khan Jan 21 '14 at 06:30
  • @Khan- just right click on your label and click on inspect element... and get the id from your label tag – The Hungry Dictator Jan 21 '14 at 07:02
  • @khan inspect element comes default with crome browser also you can use firebug a plugin with Firefox which will help you a lot in your further developments. – Harshada Chavan Jan 21 '14 at 07:30

3 Answers3

3
document.getElementById("LabelId").innerText="Your Text Here"

It sounds like your element is not found on the page. Double check the ID to make sure it exists. The easiest way is to just look in the html to make sure you're using the correct Id. One thing to keep in mind when defining asp.Net labels as server side controls is that the client side Id is a concatenation of the specified id and the ids of the label's ancestors. This means you can't reference the server side id directly in JavaScript since it's only a part of the full client side Id. You may have to specify it using a wild card.

If you need to use a wild card it might be easier to do it in Jquery

$('[id*=LabelId]')

This means you have to add a script reference to JQuery though.

TGH
  • 38,769
  • 12
  • 102
  • 135
  • Thanks for quick reply Sir. I have tried this but is shows this Error."Microsoft JScript runtime error: The value of the property '$' is null or undefined, not a Function object" – Khan Jan 21 '14 at 05:07
  • He did say "This means you have to add a script reference to JQuery" which it sounds like you haven't done – sh1rts Jan 21 '14 at 05:12
  • Yes, sorry I didn't specify that you need to add Jquery for that solution. I would however make sure the element is on the page by that Id first. If you add a server side asp.net label the client side id will be a concatenation of the specified id and the ids of its ancestors. Check that first – TGH Jan 21 '14 at 05:12
2

Generation of Client IDs

View the source of your page in the browser. This will give you a good indication of how the Client ID is generated. Each element ID should be unique and with the use of Master Pages and Controls it would be very difficult for you and the .NET framework to produce such results. If you make use of Master Pages with Content Placeholders, you will notice that your element ID's are generated based on the names of the Content Placeholders they are in.

Here is a good Code Project article regarding the generation of client IDs.

Validation

In your case, using a RegularExpressionValidator will fire the page validator when the button is pressed and if valid resulting in the page being posted back to the server. It is probably best then to add the code in the Code Behind. In such cases something like @Sachin ScriptManager.RegisterStartupScript should work in the button's event handler.

Assuming you only have one field: You could convert your validator to a CustomFieldValidator and fire regex through javascript. If the value is correct, you can set the label text in javascript without having to do any postbacks, however you may loose the state of the label once the page has posted back.

Edit: jQuery

Oftentimes I reference my elements using jQuery selectors because I don't want to hassle with the generated client ID. You are able to get your elements using the Ends With Selector as follows:

var name = $('input[id$="txtName"]'); // Find an element that ends with "txtName".

Just remember that conflict may arise when you have an element ending with the same name in more than one place on a generated page.

Clarice Bouwer
  • 3,631
  • 3
  • 32
  • 55
1

In ASP.Net web forms, there is a property called ClientID for every control on the server. This is the generated Id that you can use on the client side. So to set the label on the client side for a label with <asp:label runat="server" id="label1"/>, one way that you can do is to get the clientId in a client variable using server side RegisterStartupScript -

//server side code
page_load(){
 ScriptManager.RegisterStartupScript("IDs", string.format("var labelId = '{0}';", label1.ClientID);
}

//in javascript
document.getElementById(labelId).innerHTML = 'whatever';

By the way, I have just eye-balled this code, so it might not run as is.

Domenic
  • 110,262
  • 41
  • 219
  • 271
Sachin
  • 343
  • 2
  • 8