Search code examples
asp.netcustomvalidator

using custom validators in ASP.net


I'm using ASP.net custom validator to validate if mail exists in database or not so I have a server side bool function

public void isUnique(object source, ServerValidateEventArgs args)
{
    args.IsValid = Formatters.FormatUser.AlternateMailUnique(_txtAlternateEmail.Text);    
}

and a custom validator which validates the textbox _txtAlternateEmail

<asp:TextBox ID="_txtAlternateEmail" runat="server" onkeypress="typetext();" onmouseout="textclear();"></asp:TextBox>
                        <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="_txtAlternateEmail"  OnServerValidate="isUnique"  errormessage="Mail already exists" ValidationGroup="savechanges"/>

Meanwhile the validators doesn't act as the .net validators acts, I mean that if the function isUnique returns false the page returns to server and nothing is validated.


Solution

  • You need to use Page.IsValid property - this property indicates the page validation is succeed or not.

    Apart from the isUnique() handler, you need to verify the value of Page.IsValid in button's click handler or other handle in which you want to perform action.

    For instance,

    protected void Button1_Click(object sender, EventArgs e)
      {
        if (Page.IsValid)
        {
          //your actions
         }
      }
    

    PS: Remove JavaScript attribute onmouseout="textclear()" if it clear the content of _txtAlternateEmail.