ASP. NET TextBox maxlength using VB.NET
Here we will see that how we can turn a TextBox font red after max length characters have been inserted, and also we check number of character has been inserted in the TextBox.
Here we will see that how we can turn a TextBox font red after maxlength characters have been inserted, and also we check number of character has been inserted in the TextBox. But if we go back to a black font color if they were to delete back to less than maxlength.
Drag and drop a TextBox on the page. Select TextBox and press F4 to property window.
TextMode="MultiLine"
Now add the following code in the Head section of the .aspx page.
<head runat="server">
<title></title>
<style type="text/css">
.validentry
{
background-color:#FFFFFF;
color: #000000;
}
.invalidentry
{
background-color:#FFCCCC;
color: #ff0000;
}
</style>
<script language="javascript">
function textCounter1(field, maxlimit) {
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
document.getElementById('message').className = "invalidentry";
document.getElementById('message').focus();
//alert('You have reached your maximum character limit.');
}
else {
document.getElementById('message').className = "validentry";
}
}
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit)// if too long...trim it!
field.value = field.value.substring(0, maxlimit);
else
countfield.value = maxlimit - field.value.length;
}
</script>
</head>
|
Now add the following code in the body section.
<body bgcolor="#FFFFFF">
<form name="blah" action="" method="post" runat="server">
<asp:TextBox ID="message" runat="server" name="message"onkeydown="textCounter(this.form.message,this.form.remLen,120)"
onkeyup="textCounter1(this.form.message, 120)" class="validentry"
Height="101px" TextMode="MultiLine" Width="228px"></asp:TextBox>
<br />
<input readonly type="text" name="remLen" size="3" maxlength="3" value="120"
position: absolute; style="width: 34px">Character left<br />
<br />
<br />
</form>
</body>
|
Now run the application.
Figure1
Now check number of character has been inserted in the TextBox.
Figure2
Now we can turn a TextBox font red after max length characters have been inserted in TextBox.
Figure3