Let's say you have a Text Box = TextBox1 (textMode=MultiLine etc...) and you want to validate/Limit the number of character entered by a user
Do this:
- Add a customField Validator.
- In the customValidator properties: ErrorMessage = "Your Error Message" ControlToValidate ="control you want to validate"
- Select the Event button or double click the CustomValidator on the page.
- In the code behind Enter the following:
protected void CustomValidator1_ServerValidate
(object source, ServerValidateEventArgs args)
{ if (TextBox1.Text.Length > 10)
{ args.IsValid = false;
}
else
{ args.IsValid = true;
}
}
To avoid making a trip to the server and have instant validation when tabbing or moving to another field do this.
- Return to the CustomValidator control properties and add under Behavior:
ClientValidationFunction = validateComments (or whatever text you want to call it)
- In your aspx file add a ScriptManager from the Ajax Extensions.
Then add a new Item and select JScript File
- In the script file add the following function.
Voila! if you using a master page add the SciptManager in your master page. Hope this helped.
function validateComments(sender, args)
{
if (args.Value.length > 10)
args.IsValid = false;
else
args.IsValid = true;
}
Also, Reference the file in your script manager(see below after the function).
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/validateComments.js" />
</Scripts>
</asp:ScriptManager>