Especificar la longitud máxima para el cuadro de texto multilínea


Estoy tratando de usar asp:

<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>

Quiero una forma de especificar la propiedad maxlength, pero aparentemente no hay manera posible para un multiline textbox. He estado tratando de usar JavaScript para el evento onkeypress:

onkeypress="return textboxMultilineMaxNumber(this,maxlength)"

function textboxMultilineMaxNumber(txt, maxLen) {
    try {
        if (txt.value.length > (maxLen - 1)) return false;
    } catch (e) { }
    return true;
}

Si bien funciona bien, el problema con esta función JavaScript es que después de escribir caracteres no le permite eliminar y sustituir ninguno de ellos, ese comportamiento no es deseado.

¿Tiene alguna idea de lo que podría cambiar en el código anterior para evitar ¿eso o alguna otra forma de evitarlo?

Author: Barry Michael Doyle, 2009-08-26

16 answers

Prueba este javascript:

function checkTextAreaMaxLength(textBox,e, length)
{

        var mLen = textBox["MaxLength"];
        if(null==mLen)
            mLen=length;

        var maxLength = parseInt(mLen);
        if(!checkSpecialKeys(e))
        {
         if(textBox.value.length > maxLength-1)
         {
            if(window.event)//IE
              e.returnValue = false;
            else//Firefox
                e.preventDefault();
         }
    }   
}
function checkSpecialKeys(e)
{
    if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
        return false;
    else
        return true;
}

En el control invócalo así:

<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');"  TextMode="multiLine" runat="server"> </asp:TextBox>

También puede usar la función checkSpecialKeys para validar la entrada en su implementación de javascript.

 40
Author: Raúl Roa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-26 12:29:53

Use un validador de expresiones regulares en su lugar. Esto funcionará en el lado del cliente usando JavaScript, pero también cuando JavaScript está deshabilitado (ya que la comprobación de longitud también se realizará en el servidor).

El siguiente ejemplo comprueba que el valor introducido tenga entre 0 y 100 caracteres:

<asp:RegularExpressionValidator runat="server" ID="valInput"
    ControlToValidate="txtInput"
    ValidationExpression="^[\s\S]{0,100}$"
    ErrorMessage="Please enter a maximum of 100 characters"
    Display="Dynamic">*</asp:RegularExpressionValidator>

Por supuesto, hay expresiones regulares más complejas que puede usar para adaptarse mejor a sus propósitos.

 72
Author: Alex Angas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-31 01:54:33

Rueda el tuyo propio:

function Count(text) 
{
    //asp.net textarea maxlength doesnt work; do it by hand
    var maxlength = 2000; //set your value here (or add a parm and pass it in)
    var object = document.getElementById(text.id)  //get your object
    if (object.value.length > maxlength) 
    {
        object.focus(); //set focus to prevent jumping
        object.value = text.value.substring(0, maxlength); //truncate the value
        object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
        return false;
    }
    return true;
}

Llama así:

<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>
 20
Author: scottyboiler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 14:53:41

Mantenlo simple. La mayoría de los navegadores modernos admiten un atributo maxlength en un área de texto (es DECIR, incluido), por lo que simplemente agregue ese atributo en code-behind. Sin JS, sin Jquery, sin herencia, código personalizado, sin alboroto, sin muss.

VB.Net:

fld_description.attributes("maxlength") = 255

C #

fld_description.attributes["maxlength"] = 255
 17
Author: Mike A.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-15 13:03:39

Utilice el atributo personalizado maxsize = "100"

<asp:TextBox ID="txtAddress" runat="server"  maxsize="100"
      Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
   <script>
       $("textarea[maxsize]").each(function () {
         $(this).attr('maxlength', $(this).attr('maxsize'));
         $(this).removeAttr('maxsize'); 
       });
   </script>

Esto rendirá así

<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>
 4
Author: Ashwini Jindal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-06 10:29:19

Otra forma de arreglar esto para aquellos navegadores (Firefox, Chrome, Safari) que soportan maxlength en textareas (HTML5) sin javascript es derivar una subclase del Sistema.Web.UI.WebControls.TextBox class y anula el método Render. Luego, en el método sobrescrito, agregue el atributo maxlength antes de renderizar como normal.

protected override void Render(HtmlTextWriter writer)
{
    if (this.TextMode == TextBoxMode.MultiLine
        && this.MaxLength > 0)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
    }

    base.Render(writer);
}
 3
Author: Keith K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-05 12:49:26
$('#txtInput').attr('maxLength', 100);
 2
Author: malinois,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-07 17:47:02

Probé diferentes enfoques, pero cada uno tenía algunos puntos débiles (es decir, con cortar y pegar o compatibilidad con navegadores). Esta es la solución que estoy usando en este momento:

function multilineTextBoxKeyUp(textBox, e, maxLength) {
    if (!checkSpecialKeys(e)) {
        var length = parseInt(maxLength);
        if (textBox.value.length > length) {
            textBox.value = textBox.value.substring(0, maxLength);
        }
    }
}

function multilineTextBoxKeyDown(textBox, e, maxLength) {
    var selectedText = document.selection.createRange().text;
    if (!checkSpecialKeys(e) && !e.ctrlKey && selectedText.length == 0) {
        var length = parseInt(maxLength);
        if (textBox.value.length > length - 1) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                e.returnValue = false;
            }
        }
    }
}

function checkSpecialKeys(e) {
    if (e.keyCode != 8 && e.keyCode != 9 && e.keyCode != 33 && e.keyCode != 34 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) {
        return false;
    } else {
        return true;
    }
}

En este caso, estoy llamando a multilineTextBoxKeyUp en key up y multilineTextBoxKeyDown en key down:

myTextBox.Attributes.Add("onkeyDown", "multilineTextBoxKeyDown(this, event, '" + maxLength + "');");
myTextBox.Attributes.Add("onkeyUp", "multilineTextBoxKeyUp(this, event, '" + maxLength + "');");
 2
Author: Sue Maurizio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-28 15:39:39

Echa un vistazo a esto. La única manera de resolverlo es mediante javascript como lo intentó.

EDITAR: Intente cambiar el evento a keypressup.

 1
Author: Christian13467,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-26 12:30:49

Use HTML textarea con runat="server" para acceder a él en el lado del servidor. Esta solución tiene menos dolor que usar javascript o regex.

<textarea runat="server" id="txt1" maxlength="100" />

Nota: Para acceder a la propiedad Text en el lado del servidor, debe usar txt1.Value en lugar de txt1.Text

 1
Author: Ali Gonabadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 11:14:05

Las cosas han cambiado en HTML5:

ASPX:

<asp:TextBox ID="txtBox" runat="server" maxlength="2000" TextMode="MultiLine"></asp:TextBox>

C#:

if (!IsPostBack)
{
    txtBox.Attributes.Add("maxlength", txtBox.MaxLength.ToString());
}

HTML renderizado:

<textarea name="ctl00$DemoContentPlaceHolder$txtBox" id="txtBox" maxlength="2000"></textarea>

Los metadatos para Attributes:

Resumen: Obtiene la colección de atributos arbitrarios (solo para renderizar) que no corresponden a las propiedades del control.

Devuelve: Un System.Web.UI.AttributeCollection de pares nombre y valor.

 1
Author: Kristopher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 21:02:31

El siguiente ejemplo en JavaScript / Jquery lo hará -

<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
     function count(text, event) {

         var keyCode = event.keyCode;

         //THIS IS FOR CONTROL KEY
         var ctrlDown = event.ctrlKey;

         var maxlength = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val().length;

         if (maxlength < 200) {
             event.returnValue = true;
         }
         else {

             if ((keyCode == 8) || (keyCode == 9) || (keyCode == 46) || (keyCode == 33) || (keyCode == 27) || (keyCode == 145) || (keyCode == 19) || (keyCode == 34) || (keyCode == 37) || (keyCode == 39) || (keyCode == 16) || (keyCode == 18) ||
                 (keyCode == 38) || (keyCode == 40) || (keyCode == 35) || (keyCode == 36) || (ctrlDown && keyCode == 88) || (ctrlDown && keyCode == 65) || (ctrlDown && keyCode == 67) || (ctrlDown && keyCode == 86)) 

                  {
                 event.returnValue = true;
                  }

             else {

                 event.returnValue = false;
             }
         }

     }

     function substr(text)
      {
          var txtWebAdd = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val();
          var substrWebAdd;
          if (txtWebAdd.length > 200) 
          {                 
              substrWebAdd = txtWebAdd.substring(0, 200);                                  
              $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val('');
              $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val(substrWebAdd); 

          }
     }                  

 0
Author: Nand kishor Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-26 19:31:26

Este fragmento funcionó en mi caso. Estaba buscando la solución y pensé en escribir esto para que pueda ayudar a cualquier lector futuro.

ASP

<asp:TextBox ID="tbName" runat="server" MaxLength="250" TextMode="MultiLine" onkeyUp="return CheckMaxCount(this,event,250);"></asp:TextBox>

Java Script

function CheckMaxCount(txtBox,e, maxLength)
{
    if(txtBox)
    {  
        if(txtBox.value.length > maxLength)
        {
            txtBox.value = txtBox.value.substring(0, maxLength);
        }
        if(!checkSpecialKeys(e))
        {
            return ( txtBox.value.length <= maxLength)
        }
    }
}

function checkSpecialKeys(e)
{
    if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
        return false;
    else
        return true;
}

@Raúl Roa Respuesta funcionó para mí en caso de copiar/pegar. mientras que esto lo hace.

 0
Author: Afnan Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 13:47:05
$("textarea[maxlength]").on("keydown paste", function (evt) {
            if ($(this).val().length > $(this).prop("maxlength")) {
                if (evt.type == "paste") {
                    $(this).val($(this).val().substr(0, $(this).prop("maxlength")));
                } else {
                    if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
                        evt.returnValue = false;
                        evt.preventDefault();
                    }
                }
            }
        });
 0
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-21 13:21:05

Así es como lo hicimos (mantiene todo el código en un solo lugar):

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"/>
<% TextBox1.Attributes["maxlength"] = "1000"; %>

En caso de que alguien siga usando formularios web en 2018..

 0
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 11:10:20

Puede especificar la longitud máxima para el cuadro de texto multilínea en el evento Javascript pageLoad

function pageLoad(){
                     $("[id$='txtInput']").attr("maxlength","10");
                    }

He establecido la propiedad max length de txtInput cuadro de texto multilínea a 10 caracteres en la función Javascript pageLoad ()

 0
Author: Sumit Jambhale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-13 10:42:45