9

I would like to use a customvalidator control to handle all my validation, but I can't figure out how to set the error message in the code-behind for different checks. Is this possible?

chobo
  • 31,561
  • 38
  • 123
  • 191

2 Answers2

14

You can set the error message in the OnServerValidate method as you wish based on your validation logic:

protected void customValidator1_Validate(object sender, ServerValidateEventArgs e)
{
    if (e.Value.Length < 5)
    {
        e.IsValid = true;
    }
    else
    {
        customValidator1.ErrorMessage = "Length must be less than 5.";
        e.IsValid = false;
    }
}
jdavies
  • 12,784
  • 3
  • 33
  • 33
0

For One Control you can do like this..

<!-- In Designer Page  -->
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" 
  onservervalidate="cusCustom_ServerValidate" 
  errormessage="The text must be exactly 8 characters long!" />
<br /><br />
/* In Code Behind*/
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Hari Gillala
  • 11,736
  • 18
  • 70
  • 117
  • 1
    I don't understand when will the error message will show up under the textbox! anyway I want to set it when I click on the submit buton, but how ? – Joy Dec 07 '12 at 08:03