Search code examples
c#asp.netcustomvalidator

stopping the server side execution with custom validator


I have a form with a custom validator for minimum age. I have a submit button on that form. When the custom validator kicks in, I don't want the code inside the submit button to execute so when the minimum age requirement is not met and I set the ServerValidateEventArgs args to false. Code inside the submit button gets executed

Below is my custom validator:

<asp:CustomValidator Display="None" ID="CustomValidator1" runat="server" OnServerValidate="ageValidator" ControlToValidate="txtDOB" ErrorMessage="CustomValidator"  />

below is my date of birth text box:

<input   id="txtDOB" placeholder="mm/dd/yyyy" type="text" data-role="datebox" value="" runat="server"  ></input>

I also have submit button on that page:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" data-icon="check" OnClick="btnSubmit_Click" UseSubmitBehavior="true"   />

below is my custom validator code:

protected void ageValidator(object source, ServerValidateEventArgs args)
{
    DateTime dtStart = DateTime.Parse(txtDOB.Value.ToString());
    TimeSpan sp = DateTime.Now - dtStart;

    if (sp.Days < 16 * 365)
    {
        args.IsValid = false;
        CustomValidator1.ErrorMessage = "You have to be at least 16 ";
        return ;
    }
    else
        args.IsValid = true;
}

protected void btnSubmit_Click(object sender, System.EventArgs e)
{
    // some code here
}

when I click on the submit button, the custom validator code gets executed and then whether the args is true or false, the code in submit button gets executed. I don't want the code in submit button to be executed if args is false, but this is not happening.


Solution

  • Inside btnSubmit_Click you can test for Page.IsValid (which your custom validator setting to false) and decide whether or not to do anything else based on that answer.