Custom validator fires but does not prevent postback

Hoppe picture Hoppe · Nov 17, 2011 · Viewed 14k times · Source

I've seen a lot of questions about this already, but I'm stumped! Please help!

I have a customvalidator. It's firing but it's not preventing postback. Please help me in doing so! I can see that console.log registers before the post. But, it posts back anyway. How do I prevent the postback?

I've tried adding a control to validate, and validate empty text equal to true. I also tried adding e.preventdefault, which did not work :(

How can I prevent the postback?

    <script type="text/javascript">
//<![CDATA[
function validateWhyUnlikely(source, args) {
    console.log(1);
    args.isValid = false;
}
//]]>

<asp:TextBox ID="txtWhyUnlikely" runat="server" Rows="4" cols="20"
            CssClass="surveyTextArea" />
<asp:CustomValidator runat="server" ID="cfvWhyUnlikley" ErrorMessage="Please provide a reason since you rated an item as unlikely to provide."
        CssClass="surveyError surveySmallIndent" Display="Dynamic" 
        ClientValidationFunction="validateWhyUnlikely" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="smallSpecial" OnClick="btnSubmit_Click" />


jQuery(document).ready(function () {
    jQuery('#<%= btnSubmit.ClientID %>').click(function (e) {
        if (Page.IsValid == false) {
            console.log(false);
            e.preventDefault();
            return false;
        }
    });
});

Answer

Kelsey picture Kelsey · Nov 17, 2011

Everything looks ok althought I am not sure why you are attaching the Click function to your submit button. I would remove that and test it as it maybe be overriding the default behavior.

Also I think you need to capitalize the IsValid property:

args.IsValid = false;