0

A very strange problem, I have a text box in aspnet web form. I use jquery to validate the textbox. If it doesn't pass the validation then an red warning displays by the text box. So far so good if I click anywhere in the page and suppose I intended to type an invalid text for test.

My code:(UPDATED)

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextUserName.ClientID%>").blur(function () {
            ValidateUserNameAfterBlur();
        });
    });

    function ValidateUserName() {
        $.ajax({ type: "POST",
            url: "../UserNameWebService.asmx/ValidateUserName",
            data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                return data;
            }
        });
    }

    function ValidateUserNameBeforeSubmitting() {
        isValid = ValidateUserName();
        return isValid;
    }

    function ValidateUserNameAfterBlur() {
        isValid = ValidateUserName();
        $('#TextUserNameError').toggle(!isValid);
    }



</script>

Some other markup code:

 <td class="style4">
            <asp:TextBox ID="TextUserName" runat="server"></asp:TextBox>
        </td>
        <td>
            <span id="TextUserNameError" style="display:none; color:Red; font-weight:bold;">This is not a valid username</span>
        </td>

However there is an asp.net button on the web page. After I clicked the button, the error did show up, but it then disappeared quickly.

The button's code:

 <p>
    <asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
        CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />
</p>

I believe that it is caused by postback but no clue. Appreciate help from experts.

ADDED Image debug

And data.d

1 Answers1

1

I believe you are correct, this is happening because when you click the button (I am assuming it is a submit button?) the page performs a postback. A simple way to prevent the page from posting back when javascript validation fails is to have the javascript function return 'false'. This will prevent the page from performing the postback.

That said, I am not sure why you are hooking up your user name validation to document.click. It seems like your page will perform the validation each time the user clicks on the page, regardless of whether the value has changed.

The accepted method of performing client-side validation of user-entered text is when the control in question loses focus. In JQuery, this would be blur(). This way your validation is run only when the user has finished changing the value in the control.

This would be your button code (note the OnClientClick):

<asp:Button ID="btnSubmit" runat="server" OnClientClick="return ValidateUserNameBeforeSubmitting();" />

Your javascript should look like this:

    $(document).ready(function () {
        $("#<%=TextUserName.ClientID%>").blur(function () {
            ValidateUserNameAfterBlur();
        });
    });

    function ValidateUserName() {
        $.ajax({ type: "POST",
            url: "../UserNameWebService.asmx/ValidateUserName",
            data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                return data;
            }
        });
    }

    function ValidateUserNameBeforeSubmitting() {
        isValid = ValidateUserName();
        return isValid;
    }

    function ValidateUserNameAfterBlur() {
        isValid = ValidateUserName();
        //DISPLAY ERROR MESSAGE
    }

[UPDATED]

WORKING EXAMPLE - A value of "123" will return true for validation. Everything else will return false.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        $("#TextUserName").blur(function () {
            ValidateUserNameAfterBlur();
        });
    });

    function ValidateUserName() {
        return $("#TextUserName").val() == "123";

//      $.ajax({ type: "POST",
//          url: "../UserNameWebService.asmx/ValidateUserName",
//          data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
//          contentType: "application/json; charset=utf-8",
//          dataType: "json",
//          async: false,
//          success: function (data) {
//              return data;
//          }
//      });
    }

    function ValidateUserNameBeforeSubmitting() {
        isValid = ValidateUserName();
        $('#TextUserNameError').toggle(!isValid);
         return isValid;
    }

    function ValidateUserNameAfterBlur() {
        isValid = ValidateUserName();
        $('#TextUserNameError').toggle(!isValid);
    }



</script></head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextUserName" runat="server" />
        <div ID="TextUserNameError" style="display: none;" >Ooops!</div>
        <br />
        <asp:Button UseSubmitBehavior=true ID="btnSubmit" runat="server" OnClientClick="return ValidateUserNameBeforeSubmitting();" />
    </div>
    </form>
</body>
</html>
Shai Cohen
  • 6,074
  • 4
  • 31
  • 54
  • It is a submit button. How to change the jquery code? Adding OnError? –  Apr 30 '12 at 20:18
  • Use the OnClientClick attribute on the submit button. When the user clicks the button, OnClientClick is run before the postback. You should run your UserNameValidation code there. If the validation passes, have the javascript function return "return true;". If the validation fails, have the javascript function return "return false;". By returning "false" to OnClientClick, this will prevent the page from posting back. – Shai Cohen Apr 30 '12 at 20:26
  • But I want to use this submit button to save data to the database. Can we do it on the client side? –  Apr 30 '12 at 20:33
  • The button will still be used to save data using the postback. I am assuming you want to prevent a postback if the user name is invalid, correct? – Shai Cohen Apr 30 '12 at 20:38
  • No problem, I'll add some code to my answer. Just one question first, where do you check the results of the ajax call? Does the ajax call return true/false or something else? – Shai Cohen Apr 30 '12 at 20:50
  • It is a bool value, return true or false. –  Apr 30 '12 at 20:53
  • Still not working. The message vanished afetr clicking the button. –  May 01 '12 at 12:19
  • Can you update your original answer with the new code? It's probably something small we are overlooking. – Shai Cohen May 01 '12 at 16:03
  • After clicking the button, the code went to Page_Load immediately. –  May 01 '12 at 17:29
  • I understand. The only way I can continue helping and find out what the problem is, is if you edit your original answer with the new code. That way I can see where we are going wrong. – Shai Cohen May 01 '12 at 17:33
  • Sorry, I missed your point. What do you mean original answer with the new code? –  May 01 '12 at 17:41
  • Sorry. I meant update your original **question** with the current code. – Shai Cohen May 01 '12 at 17:42
  • Your code looks good. Let's try this: put a breakpoint in the `ValidateUserNameBeforeSubmitting` function, on the line `return isValid;`. What is the value of isValid? – Shai Cohen May 01 '12 at 18:08
  • It is "underfined" even I modified it as var isValid. –  May 01 '12 at 18:18
  • Ok. That's our problem. Can you add the code for UserNameWebService.asmx/ValidateUserName to your question? Chances are our problem starts there. – Shai Cohen May 01 '12 at 18:22
  • It is too long, I stepped into the code and found it did return "false". I suspected that javascript calling code is wrong. It could be return data.d instead of return "data". I tried it but still wrong. Should we defind it first? var isValid = new Boolean;? –  May 01 '12 at 18:34
  • If you put a breakpoint in the `ValidateUserName` function, on the `return data;` line, what is the value of **data**? – Shai Cohen May 01 '12 at 18:36
  • See the image, data is an object. –  May 01 '12 at 18:41
  • Keeping the breakpoint in the same place, type this in the javascript console: "typeof data.d". Is is boolean or string? I suspect it is string, which would explain our problem. – Shai Cohen May 01 '12 at 18:46
  • 1
    Please see ithe image I added, and the explaintion of data.d. http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/ –  May 01 '12 at 18:52
  • Learn something new every day. Have a point for that. :) I updated my answer with a full working example. Try it, you will see how it is supposed to work. From there I'm sure you can figure out where the issue is. – Shai Cohen May 01 '12 at 20:42
  • Got a solution at http://stackoverflow.com/questions/10414111/to-prevent-postback-failed-isvalid-undefined. I can mark your solution as an answer. Thanks. –  May 02 '12 at 13:08
  • Thanks. Question: In the answer you linked to, the problem was that the ajax call was asynchronous, when it should have been synchronous: `async: false`. Looking at the code you posted, you already set that parameter correctly. – Shai Cohen May 02 '12 at 16:27