You can combine the MaxLength
property of the text box for user convenience, and the RegularExpressionValidator
for client and server-side validation.
<asp:TextBox ID="textbox" runat="server" MaxLength="255" />
<asp:RegularExpressionValidator ID="regtext" runat="server"
ControlToValidate="textbox"
ValidationExpression="^.{0,255}$" />
If client-side validation fails, a postback is prevented. If javascript is disabled, or your client is an attacker, validation still occurs on the server side.
To query the page on the server-side to see if validation succeeded, check the IsValid
property on the page, and take action accordingly.
You can check out this resource for an example of IsValid
usage.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid.aspx