Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 3.5 > ASP.NET 3.5 Basics
|
ASP.NET 3.5 Basics If you are new to ASP or ASP.NET programming with version 3.5, this is the forum to begin asking questions. Please also see the Visual Web Developer 2008 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 3.5 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old March 1st, 2010, 12:44 PM
Authorized User
 
Join Date: Jul 2009
Posts: 61
Thanks: 15
Thanked 1 Time in 1 Post
Default Resricting the number of characters entered into a multiline text box

Hi
I want to limit the number of characters a user can enter into a multiline text box.
using maxlength=nnn seems to achieve this but simply prevents anymore data being entered.
Is there a way of eg turning the box red and displaying a 'too many characters entered' message, or displaying Maxc- chars - Chars left at the top of the box and preventing the form from being submitted until the box is within limits?
__________________
Geoff Baldwin
 
Old March 1st, 2010, 02:16 PM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

Complete example below.

As a security precaution, I did not include the jQuery reference in the code. So, to make this work, where it says "insert jQuery here" you need to put
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"

Code:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>TextBoxSample</title>
   <style type="text/css">
      .tooMany {
         background-color: #E7CACA;
      }
      .warn {
         font-weight: bold;
         color: #FF0000;
      }
   </style>
   <script type="text/javascript" src="insert jQuery here"></script>
   <script type="text/javascript">
      $(document).ready(function () {
         var limit = 50;
         var $textBox = $('#TextBox1');
         $textBox.keyup(function () {
            var len = $(this).val().length;
            if (len > limit) {
               $(this).addClass('tooMany');
               $('#lblStatus').text(len - limit + " characters over!").addClass('warn');
               $('#btnSubmit').attr('disabled', true);
            }
            else {
               $(this).removeClass('tooMany');
               $('#lblStatus').text(Math.abs(len - limit) + " characters left").removeClass('warn');
               $('#btnSubmit').attr('disabled', false);
            }
         });
      });
 
   </script>
</head>
<body>
   <form id="form1" runat="server">
      <asp:Label ID="lblStatus" runat="server" />
      <p>
         <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" />
      </p>
      <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
   </form>
</body>
</html>
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}
 
Old March 1st, 2010, 03:59 PM
Authorized User
 
Join Date: Jul 2009
Posts: 61
Thanks: 15
Thanked 1 Time in 1 Post
Default

Thanks Lee
I am a beginner at this but looking at your example it seems to me that it is specific to just one text box on a form.
Does this mean I have to repeat the complete java script for each textbox I want to control?

Also, I have a number of pages where this scenario crops up.
Is there a way to centralise some code that can be 'called' within the code below?
Code:
      <asp:TemplateField HeaderText="BusinessDescription*" 
        SortExpression="BusinessDescription">
        <ItemTemplate>
          <asp:Label ID="lbBusDesc" runat="server" type="multiline" Width="500" Height="100"
            Text='<%# Bind("BusinessDescription") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox ID="tbBusDesc1" runat="server" type="multiline" Width="500" Height="100" Text='<%# Bind("BusinessDescription") %>' MaxLength="500"></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a description of the business" ControlToValidate="tbBusDesc1" Text="*"></asp:RequiredFieldValidator>
        </EditItemTemplate>
        <InsertItemTemplate>
          <asp:TextBox ID="tbBusDesc2" runat="server" type="multiline" Width="500" Height="100" Text='<%# Bind("BusinessDescription") %>' MaxLength="500"></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter a description of the business" ControlToValidate="tbBusDesc2" Text="*"></asp:RequiredFieldValidator>
        </InsertItemTemplate>
      </asp:TemplateField>
__________________
Geoff Baldwin
 
Old March 1st, 2010, 04:05 PM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

It would be easy to apply this to all textboxes on a given page, by altering the jQuery selector. And, you could centralize it across pages by making it into a jQuery plugin.
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}
 
Old March 1st, 2010, 07:08 PM
Authorized User
 
Join Date: Jul 2009
Posts: 61
Thanks: 15
Thanked 1 Time in 1 Post
Default

Sorry Lee,
I did say I was a beginner :(

I now have a page that looks like the code below.

I wanted the restriction to apply to the Business Description text box for both edit and insert.
I altered the :var $textBox = $('#tbBusdesc2'); to var $textBox = $('#tbBusdesc', '#tbBusdesc1', '#tbBusdesc2'); and when this didn't wotk tried just the single value.
This doesn't work either.
Obviously missing the obvious somewhere?
I use VB as you see rather than the C~ of your sample page -- but your code is Java so shouldn't make any difference - right?
Code:
<%@ Register Assembly="System.Web.DynamicData, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  Namespace="System.Web.DynamicData" TagPrefix="cc1" %>
  
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
      .tooMany {
         background-color: #E7CACA;
      }
      .warn {
         font-weight: bold;
         color: #FF0000;
      }
   </style>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
   <script type="text/javascript">
     $(document).ready(function() {
       var limit = 9;
       var $textBox = $('#tbBusdesc2');
       $textBox.keyup(function() {
         var len = $(this).val().length;
         if (len > limit) {
           $(this).addClass('tooMany');
           $('#lblStatus').text(len - limit + " characters over!").addClass('warn');
           $('#btnSubmit').attr('disabled', true);
         }
         else {
           $(this).removeClass('tooMany');
           $('#lblStatus').text(Math.abs(len - limit) + " characters left").removeClass('warn');
           $('#btnSubmit').attr('disabled', false);
         }
       });
     });
 
   </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpmainContent" Runat="Server">
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate> 
  <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
    DataKeyNames="RecordID" DataSourceID="SqlDataSource1" DefaultMode="Insert" 
    Height="50px" Width="125px">
    <Fields>
      <asp:BoundField DataField="RecordID" HeaderText="RecordID" 
        InsertVisible="False" ReadOnly="True" SortExpression="RecordID" />
      <asp:TemplateField HeaderText="BusinessName *" SortExpression="BusinessName">
        <ItemTemplate>
          <asp:Label ID="lblBusName" runat="server" Text='<%# Bind("BusinessName") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox ID="tbBusName" runat="server" width="200" Text='<%# Bind("BusinessName") %>'></asp:TextBox>
          <asp:RequiredFieldValidator ID="rfBusinessname1" controltovalidate="tbBusname" runat="server" ErrorMessage="Please Enter a Business Name" Text="*"></asp:RequiredFieldValidator>
        </EditItemTemplate>
.............various other fields,............
 <asp:TemplateField HeaderText="BusinessDescription*" 
        SortExpression="BusinessDescription">
        <ItemTemplate>
          <asp:Label ID="lbBusDesc" runat="server" type="multiline" Width="500" Height="100"
            Text='<%# Bind("BusinessDescription") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox ID="tbBusDesc1" runat="server" type="multiline" Width="500" Height="100" Text='<%# Bind("BusinessDescription") %>' ></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a description of the business" ControlToValidate="tbBusDesc1" Text="*"></asp:RequiredFieldValidator>
        </EditItemTemplate>
        <InsertItemTemplate>
          <asp:TextBox ID="tbBusDesc2" runat="server" type="multiline" Width="500" Height="100" Text='<%# Bind("BusinessDescription") %>' ></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter a description of the business" ControlToValidate="tbBusDesc2" Text="*"></asp:RequiredFieldValidator>
        </InsertItemTemplate>
      </asp:TemplateField>
     
      <asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
    </Fields>
  </asp:DetailsView>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ChamberofCommerceConnectionString %>" 
    DeleteCommand="DELETE FROM [Members] WHERE [RecordID] = @RecordID" 
    InsertCommand="INSERT INTO [Members] ([BusinessName], [Address1], [Address2], [Locality], [City], [PostCode], [ContactFirstname], [ContactTitle], [ContactLastName], [eMail], [Telephone], [MobilePhone], [WebAddress], [Classification], [BusinessType], [BusinessDescription]) VALUES (@BusinessName, @Address1, @Address2, @Locality, @City, @PostCode, @ContactFirstname, @ContactTitle, @ContactLastName, @eMail, @Telephone, @mobilePhone, @WebAddress, @Classification, @BusinessType, @BusinessDescription)" 
    SelectCommand="SELECT [RecordID], [BusinessName], [Address1], [Address2], [Locality], [City], [PostCode], [ContactFirstname], [ContactTitle], [ContactLastName], [eMail], [Telephone], [MobilePhone], [WebAddress], [Classification], [BusinessType], [BusinessDescription] FROM [Members] WHERE ([RecordID] = @RecordID)" 
    UpdateCommand="UPDATE [Members] SET [BusinessName] = @BusinessName, [Address1] = @Address1, [Address2] = @Address2, [Locality] = @Locality, [City] = @City, [PostCode] = @PostCode, [ContactFirstname] = @ContactFirstname, [ContactTitle] = @ContactTitle, [ContactLastName] = @ContactLastName, [eMail] = @eMail, [Telephone] = @Telephone, [MobilePhone] = @MobilePhone, [WebAddress] = @WebAddress, [Classification] = @Classification, [BusinessType] = @BusinessType, [BusinessDescription] = @BusinessDescription WHERE [RecordID] = @RecordID">
    <SelectParameters>
      <asp:QueryStringParameter Name="RecordID" QueryStringField="Id" Type="Int32" />
    </SelectParameters>
    <DeleteParameters>
      <asp:Parameter Name="RecordID" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
      <asp:Parameter Name="BusinessName" Type="String" />
      <asp:Parameter Name="Address1" Type="String" />
      <asp:Parameter Name="Address2" Type="String" />
      <asp:Parameter Name="Locality" Type="String" />
      <asp:Parameter Name="City" Type="String" />
      <asp:Parameter Name="PostCode" Type="String" />
      <asp:Parameter Name="ContactFirstname" Type="String" />
      <asp:Parameter Name="ContactTitle" Type="String" />
      <asp:Parameter Name="ContactLastName" Type="String" />
      <asp:Parameter Name="eMail" Type="String" />
      <asp:Parameter Name="Telephone" Type="String" />
      <asp:Parameter Name="MobilePhone" Type="String" />
      <asp:Parameter Name="WebAddress" Type="String" />
      <asp:Parameter Name="Classification" Type="String" />
      <asp:Parameter Name="BusinessType" Type="String" />
      <asp:Parameter Name="BusinessDescription" Type="String" />
      <asp:Parameter Name="RecordID" Type="Int32" />
    </UpdateParameters>
    <InsertParameters>
      <asp:Parameter Name="BusinessName" Type="String" />
      <asp:Parameter Name="Address1" Type="String" />
      <asp:Parameter Name="Address2" Type="String" />
      <asp:Parameter Name="Locality" Type="String" />
      <asp:Parameter Name="City" Type="String" />
      <asp:Parameter Name="PostCode" Type="String" />
      <asp:Parameter Name="ContactFirstname" Type="String" />
      <asp:Parameter Name="ContactTitle" Type="String" />
      <asp:Parameter Name="ContactLastName" Type="String" />
      <asp:Parameter Name="eMail" Type="String" />
      <asp:Parameter Name="Telephone" Type="String" />
      <asp:Parameter Name="MobilePhone" Type="String" />
      <asp:Parameter Name="WebAddress" Type="String" />
      <asp:Parameter Name="Classification" Type="String" />
      <asp:Parameter Name="BusinessType" Type="String" />
      <asp:Parameter Name="BusinessDescription" Type="String" />
    </InsertParameters>
  </asp:SqlDataSource>
  <asp:SqlDataSource ID="sdsClassification" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ChamberofCommerceConnectionString %>" 
    SelectCommand="SELECT [RecordID], [Classification] FROM [Classification] order by [classification]">
  </asp:SqlDataSource>
  <p>* Indicates a required Field</p>
  <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
    ShowMessageBox="True" ShowSummary="False" />
  </ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
__________________
Geoff Baldwin
 
Old March 1st, 2010, 07:38 PM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

What I gave you was just a proof-of-concept of one way someone could go about doing this. It's not likely that taking my code and placing it into your page would work without a fair bit of modification.

Quite frankly, having seen your code and what you're trying to do, I would consider a different approach using CustomValidators on the textboxes in question.

http://msdn.microsoft.com/en-us/libr...validator.aspx

Since you're already using RequiredFieldValidators, that would make sense for this situation.

It seems all you're trying to do is to validate that the Business Description field has less than a certain number of characters. You could easily write a custom method for the CustomValidator that would get the length of the string in the textbox it is attached to, and only pass the validation if that length is below a given limit. The CustomValidator works exactly like the other validators -- it will prevent the postback if validation fails, and you can display a message with it.
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}
The Following User Says Thank You to Lee Dumond For This Useful Post:
SouthendSupporter (March 2nd, 2010)
 
Old March 2nd, 2010, 08:45 AM
Authorized User
 
Join Date: Jul 2009
Posts: 61
Thanks: 15
Thanked 1 Time in 1 Post
Default

Sorry all -- I really am a newbie and am learning on project.

I have put a custom validator in the page and included ClientValidationFunction="ValidateText10"

I have created the following in my VB Code behind page(after poking around the net for inspiration and converting something I found in C#):
Code:
Protected Sub ValidateText10(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        
        Dim numOfWords As String() = args.Value.Split(New Char() {" "c})
        args.IsValid = numOfWords.Length <= 10
    End Sub
The length of 10 is simply to ease testing!
I get no errors in the code indicated.

I have several other fields with validation controls and I use a message box to display errors.

If I leave all the other fields empty but I enter some text into the text box I get no errors displayed (if I leave the box empty I get the summarry box inc a message asking to enter a description into the text box.)
So 1 character in the textbox stops the other validations being displayed. More than 10 does not result in an error being displayed.

So, either I am not calling the function correctly, or there is someting wrong ihn the function.
I guess the ServerValidateEventArgs is incorrect as I am validating on ther client but cannot spot anything that I recognise as probably right in the coding prompts.
__________________
Geoff Baldwin
 
Old March 2nd, 2010, 09:01 AM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

You can't use ClientValidationFunction here. The ClientValidationFunction is meant to point to a JavaScript function that performs validation on the client side. Since your validation function is running on the server in this case, use OnServerValidate instead.

Code:
 
<asp:CustomValidator id="CustomValidator1"
           ControlToValidate="TextBox1"
           Display="Static"
           ErrorMessage="Too many words!"
           OnServerValidate="ValidateText10"
           runat="server"/>
(Note that the ValidateText10 function you wrote is checking for the number of words, not characters.)
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}
The Following User Says Thank You to Lee Dumond For This Useful Post:
SouthendSupporter (March 2nd, 2010)
 
Old March 2nd, 2010, 10:14 AM
Friend of Wrox
 
Join Date: May 2006
Posts: 107
Thanks: 1
Thanked 8 Times in 7 Posts
Default

You can check the length of a field with len()

Code:
Dim TBCount AsInteger = 0
TBCount = Len(TextBox1.Text)
Perform that check on submission and you can then prevent the data being submitted.


Sample Below
Code:
<%@PageLanguage="VB"AutoEventWireup="false"CodeFile="Default11.aspx.vb"Inherits="Default11" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:TextBoxID="TextBox1"runat="server"MaxLength="500"TextMode="MultiLine"></asp:TextBox>
<br/>
<br/>
<asp:LabelID="ErrorLabel1"runat="server"Text="Too Many Characters... "Visible="False"></asp:Label>
<br/>
<br/>
<asp:ButtonID="Button1"runat="server"Text="Check Before Submit"/>
</div>
</form>
</body>
</html>

Code:
 
Imports System.Drawing
PartialClass Default11
Inherits System.Web.UI.Page
ProtectedSub Button1_Click(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Button1.Click
Dim TBCount AsInteger = 0
TBCount = Len(TextBox1.Text)
If TBCount > 400 Then
TextBox1.BackColor = Color.Blue
ErrorLabel1.Visible = True
Else
TextBox1.BackColor = Color.White
ErrorLabel1.Visible = False
EndIf
EndSub
EndClass
__________________
Try our latest project www.nobanx.com Currency Exchange for members
 
Old March 2nd, 2010, 10:23 AM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

timeware's code won't work for this. The whole idea of validation is to PREVENT the default postback if validation fails.
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}





Similar Threads
Thread Thread Starter Forum Replies Last Post
max length property of multiline text box MunishBhatia ASP.NET 2.0 Professional 5 June 14th, 2007 01:55 AM
åäö Characters in Text Box itHighway Classic ASP Basics 1 August 5th, 2006 01:54 AM
put a limit on the number of characters entered in crmpicco HTML Code Clinic 6 April 12th, 2005 06:08 AM
VS.NET - Using a multiline text box VSnewbie Classic ASP Databases 3 September 10th, 2004 09:50 AM
Multiline Text in Rich TextBox Niaz Pro VB 6 3 March 1st, 2004 07:57 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.