Dave Brock Dave Brock - 5 months ago 10
Javascript Question

Validate: remove custom success message when error occurs

I am using jQuery validate to use a remote call to check if a username exists. Like this:

remote: {
url: "MyUrl",
type: "GET",
complete: function (data) {
// Return success message if applicable
if (data.responseText == "true")
{
$("#divUserNameAvailable").show();
}
}
}


But if I stay in the field and force a validation error, the message stays.

enter image description here

Here is the full validation:

if ($("#CreateAccountForm").length) {
$("#CreateAccountForm").validate({
rules: {
UserName: {
required: true,
rangelength: [6, 20],
usernameFilter: true,
remote: {
url: "MyUrl",
type: "GET",
complete: function (data) {
// Return success message if applicable
if (data.responseText == "true")
{
$("#divUserNameAvailable").show();
}
}
}
},
},
messages: {

UserName: {
remote: "This username is not available. Please enter a new username.",
required: "Please enter your username.",
rangelength: "Usernames must be between 6 and 20 characters in length and may not use any special characters such as \\ / + {{ }} [ ] | = , * ? ; : < > @."
},

},

errorPlacement: function (error, element) {
error.insertAfter(element);
},
submitHandler: function (form) {
form.submit();
}
});


I try to hide the DIV in the errorPlacement, but nothing works. Any ideas?

Answer

If it is a successful call, then hide the error <div>:

remote: {
    url: "MyUrl",
    type: "GET",
    complete: function (data) {
        // Return success message if applicable
        if (data.responseText == "true")
        {
            $("#divUserNameAvailable").show();
            // Hide the error div. Replace the `that_error_div_selector` with right selector.
            $(that_error_div_selector).hide();
        }
    }
}