Doozer Blake
Doozer Blake

Reputation: 7797

Can I run some custom script after ASP.NET client side page validation fails?

I'm trying to run some client side script if, and only if, the client side Page validation fails, and can't figure out where I can hook it in.

If i bind my JavaScript function to the OnClientClick of the button that submits the form, it runs before the client side validation. If I bind it to the OnSubmit of the form, that only fires if the validation passes.

Any ideas of how or where I can hook something like this up? Or if you have other suggestions, I'm open to them.

<form id="frm" runat="server" 
     onsubmit="FUNCTION HERE WONT FIRE IF VALIDATION FAILS">
<asp:requiredfieldvalidator id="vld" runat="server" controltovalidate="txt"/>
<asp:textbox id="txt" runat="server"></asp:textbox>

<asp:button id="cmd" runat="server" OnClick="dosomething"
     OnClientClick="FUNCTION FIRES BEFORE VALIDATION OCCURS">

</form>

Upvotes: 14

Views: 9938

Answers (3)

IUnknown
IUnknown

Reputation: 22458

Add script below at the end of page's markup file:

var originalValidationFunction = Page_ClientValidate;
if (originalValidationFunction && typeof (originalValidationFunction) == "function") {
    Page_ClientValidate = function (validationGroup) {
        originalValidationFunction(validationGroup);

        if (!Page_IsValid) {
            // your code here
            alert("oops!");
        }
    };
}

Upvotes: 16

James Johnson
James Johnson

Reputation: 46057

Try using Page_ClientValidate("") to trigger validation from JavaScript, and then you can run some custom code:

validate = function(){
    var isValid = Page_ClientValidate(""); //parameter is the validation group - thanks @Jeff
    if (isValid){
        isValid = somethingToCheck();
    }
    return isValid;
}

<asp:Button ID="Button1" runat="server" CausesValidation="false" OnClientClick="return validate();" ... />

Upvotes: 14

sll
sll

Reputation: 62524

So you have two options how to handle it:

  1. Use CustomValidator validator which provides ClientValidationFunction feature and inside your custom validation function obviously you know whether validation failed. It gives you as much as you need flexibility on client side validation by accepting a JavaScript function to be used whilst validation.

  2. Check validator satus by accessing it via JavaScript by accessing validator's isValid property from JavaScript (+jQuery):

 var anonymousValidator = $("#<%= vldCommentText.ClientID %>")[0];
 ValidatorEnable(anonymousValidator, true);
 if (!anonymousValidator.isvalid) 
 {
     // ...
 }

Upvotes: 2

Related Questions