Custom validator fires but does not prevent postba

2019-06-19 02:04发布

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;
        }
    });
});

8条回答
神经病院院长
2楼-- · 2019-06-19 02:51

Posting this as it might help someone that is getting the same weird behavior.

Initially I had the same issue as this post title. I checked all the suggestions here but my code seemed to be fine.

To fix this I replaced my cause validation control <asp:Button.. with a <button.. . Not sure why this is happening but happy it's working now.

hth

查看更多
时光不老,我们不散
3楼-- · 2019-06-19 02:52

<button tags are missing the correct javascript code to validate. <asp:Button does have the correct javascript rendered.

I've added this to any button tags:

btn.Attributes("onclick") = StringFmt("if(!Page_ClientValidate(''))return false;")

and that solved the post-back issue. No post-back occurs if the client-side detects an issue.

查看更多
登录 后发表回答