asp.net textbox multiline maxlength

asp.net - Especificación de maxlength para cuadro de texto multilínea



textbox multiline (14)

Echa un vistazo a this . La única forma de resolverlo es javascript como lo has intentado.

EDITAR: Intente cambiar el evento a keypressup.

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 forma de que sea posible un multiline textbox maxlength . 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; }

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

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


El siguiente ejemplo en JavaScript / Jquery hará eso-

<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); } }


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

ÁSPID

<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 La respuesta me funcionó en caso de copiar / pegar. mientras esto lo hace.


Intenté diferentes enfoques, pero todos tenían algunos puntos débiles (es decir, con la compatibilidad de cortar y pegar o del navegador). 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, invoco multilineTextBoxKeyUp en la tecla arriba y multilineTextBoxKeyDown en la tecla:

myTextBox.Attributes.Add("onkeyDown", "multilineTextBoxKeyDown(this, event, ''" + maxLength + "'');"); myTextBox.Attributes.Add("onkeyUp", "multilineTextBoxKeyUp(this, event, ''" + maxLength + "'');");


Las cosas han cambiado en HTML5:

ASPX:

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

DO#:

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

HTML procesado:

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

Los metadatos para los Attributes :

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

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


Otra forma de corregir esto para esos navegadores (Firefox, Chrome, Safari) que admiten maxlength en textareas (HTML5) sin javascript es derivar una subclase de la clase System.Web.UI.WebControls.TextBox y anular el método Render. Luego, en el método reemplazado, agregue el atributo maxlength antes de renderizar de la forma habitual.

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


Tira el tuyo:

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; }

Llamar así:

<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>


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

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

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


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

El siguiente ejemplo verifica que el valor ingresado tenga entre 0 y 100 caracteres de longitud:

<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.


mantenlo simple. La mayoría de los navegadores modernos admiten un atributo de longitud máxima en un área de texto (incluido IE), así que simplemente agregue ese atributo en código subyacente. Sin JS, sin Jquery, sin herencia, código personalizado, sin problemas, sin muss.

VB.Net:

fld_description.attributes("maxlength") = 255

DO#

fld_description.attributes["maxlength"] = 255


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, invocalo 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.


usar 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 se renderizará así

<textarea name="ctl00$BodyContentPlac eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>


$("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(); } } } });


$(''#txtInput'').attr(''maxLength'', 100);