The regular expression is no doubt the way to go, but if you wanted to
be fancy about it you could use a custom validator with an associated
class in your app_code folder. It looks like this:
This would be your aspx page:
****************************************************************************************************
<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="
http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<custom:LengthValidator ID="CustomValidator1"
controltovalidate="TextBox1" MaximumLength="10" runat="server"
text="Less than 10" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" /></div>
</form>
</body>
</html>
****************************************************************************************************
This would be your application code placed in the app_code folder:
****************************************************************************************************
Imports Microsoft.VisualBasic
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace myControls
'''<summary>
'''Validates the length of an input field
'''</summary>
Public Class LengthValidator
Inherits BaseValidator
Dim _maximumLength As Integer = 0
Public Property MaximumLength() As Integer
Get
Return _maximumLength
End Get
Set(ByVal value As Integer)
_maximumLength = value
End Set
End Property
Protected Overrides Function EvaluateIsValid() As Boolean
Dim value As String =
Me.GetControlValidationValue(Me.ControlToValidate)
If value.Length > _maximumLength Then
Return False
Else
Return True
End If
End Function
End Class
End Namespace
****************************************************************************************************
Any trouble with this implementation let me know. Its probably a bit of
overkill but can easily be customized.