Using Server Side code
<asp:TextBox ID="txtCharacters" runat="server" Text="There is a Textbox in which only 50 charactes are allowed to enter excluding spaces between the characters." />
<asp:Button Text="Save" OnClick="Save" runat="server" />
C#
protected void Save(object sender, EventArgs e)
{
string s = this.txtCharacters.Text.Trim();
s = s.Replace(" ", "");
if (s.Length > 50)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('50 characters allowd')", true);
}
}
Using JavaScript and CustomValidator
HTML
<asp:TextBox ID="txtCharacters" runat="server" Text="There is a Textbox in which only 50 charactes are allowed to enter excluding spaces between the characters." />
<asp:Button Text="Save" OnClick="Save" runat="server" ValidationGroup="Characters" />
<asp:CustomValidator ErrorMessage="Only 50 Characters" ControlToValidate="txtCharacters"
ClientValidationFunction="CharactersLengthValidation" runat="server" ValidationGroup="Characters" />
JavaScript
<script type="text/javascript">
function CharactersLengthValidation(sebder, args) {
args.IsValid = true;
var characters = args.Value;
characters = characters.replace(" ", "");
if (characters.length > 50) {
args.IsValid = false;
}
}
</script>