Custom Validator With Javascript To Validate Multiline Textbox
When we are developing application, we get a situation to provide multi line textbox.
Multi line Text box has Max Length property but it accepts the characters more then the specified Max Length.
We can restrict the user not to enter more than the specified max length in that Multi Line text box using a simple java script and Custom validator.
Java script To Validate Charecters Length:
<script language="javascript" type="text/javascript">
function validateControl(source, arguments) {
if (arguments.Value.length > 2000) {
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
}
</script>
Multi Line Textbox and Custom Validator:
<asp:TextBox ID="txtBody" CssClass="Form_Textbox" runat="server" Width="500px" TextMode="MultiLine" Rows="12" >
</asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" CssClass="Form_ErrorMessage"
SetFocusOnError="true" ControlToValidate="txtBody" ClientValidationFunction="validateControl"
Display="Dynamic" ErrorMessage="Message should not be greater than 2000 Characters."> </asp:CustomValidator>
Call the javascript function as a ClientValidationFunction of the custom validtor.
Assume we want to allow the user to enter maximum of 2000 characters in the multi line text box.
To make this functionality or feature more usable, we need to show an help message saying that the multi line text box allows maximum of 2000 characters only.
This idea is good and user knows that he can enter up to 2000 characters only.
If we can provide the number of characters entered by the user then user know how many remaining characters he can enter.
This can be achieved by a div and java script.
<script language="javascript" type="text/javascript">
function showEnteredMessageLength() {
var ctrlMessageControl = document.getElementById('<%=txtBody.ClientID%>');
var ctrldivID = document.getElementById('divCharectersCount');
if (ctrldivID != null && ctrlMessageControl != null) {
ctrldivID.innerHTML = "Total number of characters entered : " + ctrlMessageControl.value.length + " ";
}
}
</script>
We have to call the above java script from the textbox.
<asp:TextBox ID="txtBody" CssClass="Form_Textbox" runat="server" Width="500px" TextMode="MultiLine"
onmouseout="javascript:showEnteredMessageLength();" onkeypress="javascript:showEnteredMessageLength();"
onkeyup="javascript:showEnteredMessageLength();" onblur="javascript:showEnteredMessageLength();"
Rows="12" >
</asp:TextBox>
Textbox Help Message:
[Maximum number of characters allowed : 2000]
Div that shows the enterred characters count:
This div’s id is used in the javascript to show the characters count.
Total number of characters entered :0
Attachments
Custom Validator With Javascript To Validate Multiline Textbox Example (31874-27342-Multiline Text box Example.rar)