asp:CustomValidator not returning 'false'

966 views Asked by At

Don't know what is wrong here. This is a page developed by someone else and I am trying to fix one of the issue.

Scenario:

ASP.NET site.

Login.aspx has <asp:login> and there are three validation groups. Login.aspx.cs is a partial class of "user_login".

Each validation group has a textbox and an associate customvalidator. All three custom validators gets triggered when something is entered in corresponding textbox but issue is only the first textbox (bound to validationgroup = 1) returns false when validation fails.

For 2nd and 3rd, the customvalidator get triggered but when there is validation issue and even after setting "args.IsValid = false;", the process continues with what needs to be executed further.

Don't know what is going on wrong here. I would like the customvalidator to return false. Worst case, are there any ways to return the control back to the 'textbox' when validation fails?

Below is the custom validator used.

<asp:CustomValidator ID="ExistingIdValidator" runat="server" ControlToValidate="NewUserName" 
    ValidateEmptyText="true" ValidationGroup="NewUserForm" 
    OnServerValidate="NewUserNameCheck_ServerValidate">
</asp:CustomValidator> 


protected void NewUserNameCheck_ServerValidate(object source, ServerValidateEventArgs args)
{
    CustomValidator validator = source as CustomValidator;
    if (validator != null)
    {
        string NewuserNameValue = this.NewUserName.Text;
        Guid registeredUserId = (Guid)Membership.GetUser(NewuserNameValue).ProviderUserKey;
        if (registeredUserId != null)
        {
            validator.IsValid = false;
            this.FailureText_New.Text = "This UserID already exists. Please login as existing user";
            args.IsValid = false;
        }
    }
}
1

There are 1 answers

1
John Pick On

The funny thing about ASP.NET server-side validation is that it does not automatically prevent your click events from executing. It's as if the validation procedure is performed and then the results are ignored. So, the first thing to put inside your button's event is if (!Page.IsValid) return;. That's how you prevent the rest of the event from executing, and that's how you force the user to correct any mistakes on the form.