Invalidate Page via JavaScript
I have a registration form with several validator controls. I am checingk the username availability via AJAX (using jQuery, NOT an UpdatePanel). If the username is taken, I would like to make the page invalid like the other ASP.NET validators do from my JavaScript function. Is this possible? Examples?
Here is my current functionality:
// In head...
<script type="text/javascript">
$(document).ready(function () {
$('#<%= username.ClientID %>').blur(function () {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'MyService.asmx/CheckAvailability',
dataType: 'json',
data: '{ "username": "' + username + '" }',
success: function (response) {
// stuff
// If username is taken, invalidate
}, error: function () { /* stuff */ }
});
});
});
</script>
// The markup...
<dl><dt>Username</dt>
<dd>
<asp:textbox id="username" runat="server" />
<asp:requiredfieldvalidator id="usernameRequiredValidator" runat="server"
controltovalidate="username"
errormessage="Required"
开发者_如何学运维 display="Dynamic" />
<span id="avail_response"></span>
<!-- More stuff... -->
This link provides an in-depth explanation of ASP.Net validation. Scroll down to the paragraph 'The Client-Side API' where it explains that you can set the Page_IsValid variable. Be warned however, there is no guarantee that this API will stay the same in future versions of .NET so check for the existence of Page_IsValid.
EDIT :
Sorry, in my previous comment I was in a bit off a hurry and I just answered your question without looking at the bigger picture. I just reread your question and indeed, it will do nothing because when you the user clicks the submit button, it triggers a revalidation of all validators. Because the textbox username has a value, your requiredvalidator is valid and the form submits.
I think that a better solution in the long run (and one that doesn't directly call javascript functions of .NET) is the following :
- Add a hidden field
- Create a requiredfieldvalidator for that hidden field
- Place the requiredfieldvalidator behind the first requiredvalidator and give it the same errormessage as that requiredvalidator
- Place some value in the hidden field in your success function if the username is available, in all other cases, make the hidden field empty.
It's a bit of a detour but it's future proof & easier than figuring out how to do it with the javascript functions of the .NET validator framework.
精彩评论