Search code examples
c#asp.netpostbackbuttonclickcomparevalidator

Compare validator doesn't stop postback


Below is my mark up. 

<asp:TextBox ID="txtPatientDateOfBirth" runat="server" 
    CssClass="rightDivInnerControls" ClientIDMode="Static" 
    CausesValidation="True">
</asp:TextBox>
<asp:CompareValidator ID="cvPatientDateOfBirth" runat="server" 
    ErrorMessage="Enter proper date." 
    Type="Date" ControlToValidate="txtPatientDateOfBirth" Font-Bold="True"  
    Operator="DataTypeCheck"
    ValidationGroup="FirstPreview">
</asp:CompareValidator>    

<asp:Button ID="btnSaveChanges" runat="server" 
    Text="Save Changes"  OnClientClick="return showFinalReviewAlert();" 
    CssClass="btnPrimary hideInPrint btnEditFinalReport" 
    ValidationGroup="FirstPreview" 
    onclick="btnSaveChanges_Click"  ClientIDMode="Static"/>

When I change the date to a wrong format it shows me the error message immediately.

enter image description here

But when I click on the button "btnSaveChanges" it does a postback. I think something is missing because of which it is doing postback.

Can anyone please help me with the issue. I want to stop the postback if validation fails.

Thanks.


Solution

  • By returning the value of showFinalReviewAlert(); in the OnClientClick of the button, you are blocking the page validation from happening.

    This is effectively the HTML that is being rendered (simplified for viewing)...

    <input type="submit" 
           id="btnSaveChanges" 
           onclick="return showFinalReviewAlert();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnSaveChanges;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" 
           name="btnSaveChanges">
    

    The important bit of this is...

    onclick="return showFinalReviewAlert();WebForm_DoPostBackWithOptions....
    

    What it means is that no matter what showFinalReviewAlert() returns, the WebForm_DoPostBackWithOptions will never be reached. However, because it is an <input type="submit"> the page will post-pack to the server anyway.

    So, if the return value of the showFinalReviewAlert must stop the post-back from happening by returning the value false, you should set the OnClientClick attribute as this...

    OnClientClick="if(showFinalReviewAlert()==false){return false;}"
    

    In other words, if showFinalReviewAlert return false then stop the button from continuing any post-back processing... but if it return true, then allow the post-back validation to take place.

    On the other hand, if the result of showFinalReviewAlert() doesn't matter... simply remove the return to give simply...

    OnClientClick="showFinalReviewAlert();"