[英]Is there a security reason to validate a textbox input if you are limiting the max length of the input?
[英]How to disable input in TextBox after it reaches its max length
我已經將我的文本框maxlength設置為20,在這里我使用驗證控件給出錯誤消息,並且可以正常工作,但是實際上我希望它在用戶開始在文本框中輸入輸入時顯示字符計數,當它達到20個字符時,用戶應該無法輸入。 可以做到這一點嗎?
您需要為此使用Javascript:
JS
function tocheck(field, count, limit)
{
if (field.value.length > limit)
field.value = field.value.substring(0, limit);
else
count.value = limit - field.value.length;
}
Asp.net
<asp:TextBox ID="txtMessage" TextMode="MultiLine" Width="200px" Rows="3"
runat="server" onkeyup="tocheck(txtMessage, this.form.remLen, 20);" onkeydown="tocheck(txtMessage, this.form.remLen, 20);" />
在另一個文本框中,檢查計數:
<input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" />
我寫的代碼盡可能簡單。 您還需要處理其他事件,例如onPaste ,並將其寫入效率更高。 順便說說。
我假設:您有jQuery:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
這些控件:
<asp:TextBox ID="txtMessage" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Label ID="lblCount" runat="server"></asp:Label>
您只需要這樣的一些JavaScript代碼:
<script>
var max = 20;
var lblCount = $("[id$='lblCount']");
var txtMessage = $("[id$='txtMessage']");
function checkCount(padding) {
var currentLength = txtMessage.val().length;
if (currentLength >= 20) {
return false;
} else {
lblCount.text(max - currentLength - padding);
}
return true;
}
lblCount.text(max);
txtMessage.keypress(function (e) {
var key = e.keyCode || e.which;
if (key != 8 && key != 46) {
if (!checkCount(1)) {
e.preventDefault();
};
};
});
txtMessage.keyup(function (e) {
var key = e.keyCode || e.which;
if (key != 8 && key != 46) {
e.preventDefault();
return;
}
checkCount(0);
});
</script>
在JavaScript代碼的最開始部分,我定義了max,lblCount一個txtMessage,您必須了解它們。
VB.NET
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
If TextBox1.Text.Length >= 25 Then
If e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End If
End Sub
'25是極限用戶輸入
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.