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

And

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):Your javascript should look like this:
[UPDATED]
WORKING EXAMPLE – A value of “123” will return true for validation. Everything else will return false.