Para implementar la funcionalidad de contar los caracteres y limitarlos en un control de Devexpress se puede crear un archivo js para agregar las siguientes funciones:
function RecalculateCharsRemaining(editor) {
var maxLength = parseInt(editor.maxLength ? editor.maxLength : editor.GetInputElement().maxLength);
var editValue = editor.GetValue();
var valueLength = editValue != null ? editValue.toString().length : 0;
var charsRemaining = maxLength - valueLength;
SetCharsRemainingValue(editor, charsRemaining >= 0 ? charsRemaining : 0);
}
function SetCharsRemainingValue(textEditor, charsRemaining) {
var associatedLabel = ASPxClientControl.GetControlCollection().Get(textEditor.name + "_cr");
var color = GetLabelColor(charsRemaining).toString();
associatedLabel.SetText("<span style='color: " + color + ";'>" + charsRemaining.toString() + "</span>");
}
function GetLabelColor(charsRemaining) {
if (charsRemaining < 5) return "red";
if (charsRemaining < 12) return "#F3A250";
return "green";
}
// ASPxMemo - MaxLength emulation
function InitMemoMaxLength(memo, maxLength) {
memo.maxLength = maxLength;
}
function EnableMaxLengthMemoTimer(memo) {
memo.maxLengthTimerID = window.setInterval(function () {
var text = memo.GetText();
if (text.length > memo.maxLength) {
memo.SetText(text.substr(0, memo.maxLength));
RecalculateCharsRemaining(memo);
}
}, 50);
}
function DisableMaxLengthMemoTimer(memo) {
if (memo.maxLengthTimerID) {
window.clearInterval(memo.maxLengthTimerID);
delete memo.maxLengthTimerID;
}
}
Agregar la referencia a nuestro archivo js:
<script src="../Content/functions.js" type="text/javascript"></script>
Luego en el markup, agregar lo siguiente a los eventos del cliente del control:
<ClientSideEvents Init="function(s, e) { InitMemoMaxLength(s, 128); RecalculateCharsRemaining(s); }" GotFocus="EnableMaxLengthMemoTimer" LostFocus="DisableMaxLengthMemoTimer"
KeyDown="RecalculateCharsRemaining" KeyUp="RecalculateCharsRemaining" />
El segundo parámetro en la función InitMemoMaxLength es el máximo de caracteres que aceptará el control.
Luego podemos agregar un span con una etiqueta que mostrará el número de caracteres restantes de la siguiente manera:
<span class="chrm">Characters remaining: <dx:ASPxLabel ID="txtEmail_cr" runat="server" EnableClientSideAPI="True" /> </span>
El ID de la etiqueta que mostrará los caracteres restantes debera tener el mismo nombre que el control a validar mas el sufijo _cr.
Comentarios
Publicar un comentario