ASP.NET MultiLine TextBox MaxLength Validation

There have been many articles and forums addressing the fact that the MaxLength property of the ASP.NET TextBox does not work when you set TextMode to MultiLine. The majority of these solutions use the KeyPress and OnBlur events. This brings with it lots of JavaScript and a host of browser issues. I was impressed by the RegularExpressionValidator options because they can tie in to the AJAX ValidatorCalloutExtender. I also like the server-side validation that you get with the native validation controls.

The solution I settled on is a combination of all the above. I use an ASP.NET RegularExpressionValidator on the MultiLine TextBox. The code looks like this:

<asp:TextBox runat="server" ID="txtDescription" TextMode="MultiLine" Rows="5" Width="300" />
<
asp:RegularExpressionValidator runat="server" ID="revtxtDescription" ControlToValidate="txtDescription" ErrorMessage="Exceeds 500 character maximum." ValidationExpression="^[\s\S]{0,500}$" Display="None" />
<
ajax:ValidatorCalloutExtender ID="vcerevtxtDescription" runat="server" TargetControlID="revtxtDescription" />

Good so far, but to quote Mark Hildreth:

“I agree that that works for preventing users from posting too much text, however it does’t prevent them from typing more than 500 characters into the box. The validators only perform their validation in the onchange event which is not triggered on every key stroke. Imagine your dismay if you spent 10 minutes typing into a textbox, only to have the form say you have exceeded the 500 character limit?”

The JavaScript below will call this RegularExpressionValidator every second. I find that it does not noticeably slow down the form.

<script type="text/javascript">

    $(document).ready(function () {
        setInterval("validateDescription();", 1000);
    });

    function validateDescription() {
        var myValidator = document.getElementById("<%= revtxtDescription.ClientID %>");
        ValidatorValidate(myValidator);
    }

</script>

Now as the user is typing, they will be warned within one second of exceeding 500 characters. If they paste into the textbox, it will alert them too.

jQuery Get Next Textbox in a GridViewRow

In a GridView I have a column of checkboxes and a column of textboxes. I wanted to modify the value of the textbox when the checkbox is checked. jQuery is the perfect fit for this. Here is the code I used:

$(function () {
    var $inp = $('input:checkbox');
    $inp.bind('click', function () {
        var textbox = $(":input:text:eq(" + $inp.index(this) + ")");

        if (this.checked == true) {
           
textbox.val('123ABC');
            textbox.attr('disabled', 'disabled');
        } else {
            textbox.attr('disabled', '');
        }
    });
});

This post uses ideas from Suprotim Agarwal.

Setting WatermarkText in JavaScript

To set the Watermark Text of a TextBoxWatermarkExtender in the AJAX Control Toolkit, use the following code:

var behavior = $find('<%= TextBoxWatermarkExtender1.ClientID %>');
behavior.clearText();
behavior.set_Text('Hello World!');
behavior.initialize();

It took me a while to find that I needed to call the Initialize() function before the Watermark Text would get updated.


Update September 25, 2012

It appears that different versions of the AJAX Control Toolkit have different public methods.

var behavior = document.getElementById("<%= TextBox1.ClientID%>").AjaxControlToolkitTextBoxWrapper;
behavior.set_Watermark('');

http://stackoverflow.com/questions/2701875/ajaxtoolkit-textboxwatermarkextender-how-to-change-the-text-from-javascript

ASP.Net AJAX Animations

Some of the best resources for the animation framework that comes with the ASP.Net AJAX Control Toolkit can be found at the live toolkit site at this Sample Site. I often look at the Animation Reference section of this site.

While adding animations to ASP.Net pages, it is sometimes necessary to call animations directly from Javascript code. This can be achieved relatively easily using the great instructions at this MSDN blog.

Combined with the Animation Reference on http://asp.net/ajax website, any animation can be called directly from Javascript. If you can’t use the <OnLoad> animation event handler in the AnimationExtender control, one way to play animations on the page load is to use ClientScriptManager.RegisterStartupScript to create a function with the animation code, and call that function on the next line.


Page.ClientScript.RegisterStartupScript(Me.GetType, “PlayLoadAnimation”, “function playNotificationAnimation(){ AjaxControlToolkit.Animation.ColorAnimation.play($get(“”divNotification””) , 1 , 30 , “”style”” , “”backgroundColor”” , “”#181840″” , “”#E9E8FF””); }”, True)

Page.ClientScript.RegisterStartupScript(Me.GetType, “LoadAnimationFunction”, “playNotificationAnimation();”, True)

Happy Animating!
Zachary Lyons

JavaScript Code To Toggle Check Boxes

Here is some JavaScript code to toggle check boxes (same action as radio buttons).

In the page load event register the JavaScript: 

   chkTwoYear.Attributes.Add(“onclick”, “javascript: CheckTwoProgram(” + chkTwoYear.ClientID + “);”); 
   chkFourYear.Attributes.Add(“onclick”, “javascript: CheckFourProgram(” + chkFourYear.ClientID + “);”);

In the HTML of the page add the JavaScript:

<SCRIPT Language=”JavaScript”><!–
function CheckTwoProgram(id) { 
   if(id.checked) 
      document.forms[0].chkFourYear.checked=false; 
   }
function CheckFourProgram(id) { 
   if(id.checked) 
      document.forms[0].chkTwoYear.checked=false; 
   }
//–>
</SCRIPT>

How to run client side javascript on a server control

Here is some code to run a javascript function on the client side when a value changes in a drop down box. In this case I have a list of dates populating a drop down box. When the date changes the value of a DIV section changes to a corresponding end date.

In the appSetting section of the web.config file:

<add key=StartDates value=12/06/06, 02/27/07, 05/09/07, 07/03/07, 10/10/07, 01/08/08, 03/02/08/>
<
add key=EndDates value=10/08/07, 12/21/07, 03/18/08, 05/29/08, 08/18/08, 10/29/08, 01/27/09/>

In the page load section:

 ‘ Get the start and end dates from the web.config file
 
 Dim StartDates As Array
 StartDates = ConfigurationManager.AppSettings(“StartDates”).Split(“,”)
 EndDates = “‘” & ConfigurationManager.AppSettings(“EndDates”).Replace(“, “, “‘, ‘”) & “‘”  ‘ format the string for a javascript array
 EndDate = EndDates.Substring(0, EndDates.IndexOf(“,”)).Replace(“‘”, “”)
 
 ‘ Populate the Start Date drop down / combo box
 
 ddlStartDate.AppendDataBoundItems = True
 Dim Item As String
 For Each Item In StartDates
  Items = New ListItem
  Items.Text = Item
  Items.Value = Item
  ddlStartDate.Items.Add(Items)
 Next
 
 ‘ Register the javascript code to run on the client side
 
 ddlStartDate.Attributes.Add(“onchange”, “javascript: doAction(” + ddlStartDate.ClientID + “)”)

Then in the web form:

<table border =”0″><tr><td><asp:DropDownList ID=”ddlStartDate” runat=”server”></asp:DropDownList></td><td><div id=”EstCompDate”>Est. Comp. Date: <b><%=EndDate%></b></div></td></tr></table>

Then at the bottom of the HTML of the page (just above the </html> tag):

<script language=”javascript”>
var
endDates = new Array(<%=EndDates %>);
function doAction(id) {
   var selection = id.options[id.selectedIndex].value;
   EstCompDate.innerHTML =
‘Est. Comp. Date: <b>’ + endDates[id.selectedIndex] + ‘</b>’;
}
</script>