Search code examples
c#asp.netvalidationrequiredfieldvalidator

ASP.NET Required Field Validator and Compare Validator not working


None of my validators are working. Please help! Thanks in advance...

  if (rfvEmail.IsValid && rfvLoginName.IsValid && rfvNewPassword.IsValid
                && rfvConfirmPassword.IsValid && cvComparePasswords.IsValid)
            {
                DataSet ds = new DataSet();
                myDal.ClearParams();
                myDal.AddParam("@EmailAddress", txtEmail.Text);
                myDal.AddParam("@LoginName", txtLoginName.Text);
                myDal.AddParam("@NewLoginPassword", txtNewPassword.Text);
                ds = myDal.ExecuteProcedure("spResetPassword");

                lblPasswordMessage.Text = ds.Tables[0].Rows[0]["result"].ToString();                
            }

The source code looks like this: I've also set CausesValidation to true on Button

 <asp:RequiredFieldValidator
                    ID="rfvConfirmPassword"
                    runat="server"
                    ErrorMessage="Password Confirmation is required!"
                    ControlToValidate="txtConfirmPassword"
                    EnableClientScript="False"
                    ForeColor="Red"></asp:RequiredFieldValidator>                 

                <asp:CompareValidator 
                    ID="cvComparePasswords" 
                    runat="server" 
                    ControlToCompare="txtNewPassword"
                    ControlToValidate="txtConfirmPassword"
                    EnableClientScript="false"
                    ForeColor="Red"
                    ErrorMessage="Passwords entered by you do not match!">
                </asp:CompareValidator>

I'm trying to validate the controls in Save button:

 protected void btnSavePassword_Click(object sender, EventArgs e)
    {

        rfvEmail.Validate();
        rfvLoginName.Validate();
        rfvNewPassword.Validate();
        cvComparePasswords.Validate();
        resetPassword();
      }

Solution

  • At first glance it appears you are going about validation the wrong way. Without further imformation it is hard to diagnose the exact problem, so I'll provide some general advice.

    You should familiarise yourself with the APS.net Page Life Cycle. In the link provided, take note of the Load,Validation & Postback event handling staged. The Validation stage occurs automatically and will validate each of the validated controls on the page and set Page.IsValid as either true or false. This means you don't need to validate each control individualy.

    It also important to note that Validation comes after Load and before Postback event handling. It is possible to mess up the validation in the PageLoad event by assigning default values to controls. For this reason !Page.IsPosback is often used to only set controls on initial Page Load and not on subsequent postback. On postback don't reset your controls until after you've finished with them. In this instance your Click handler.

    Here is how I would do it:

    //Page Load event
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostback)
        {
            //Set Control inital page load values etc in here
        }
    }
    
    
    private void resetPassword()
    {
       //You should investigate try/catch blocks to handle database errors better
       DataSet ds = new DataSet();
       myDal.ClearParams();
       myDal.AddParam("@EmailAddress", txtEmail.Text);
       myDal.AddParam("@LoginName", txtLoginName.Text);
       myDal.AddParam("@NewLoginPassword", txtNewPassword.Text);
       ds = myDal.ExecuteProcedure("spResetPassword");
       lblPasswordMessage.Text = ds.Tables[0].Rows[0]["result"].ToString();          
    }
    
    protected void btnSavePassword_Click(object sender, EventArgs e)
    {
        if(Page.IsValid) //The controls have already been validated now
        {
            resetPassword();
    
            //If you need to empty/reset fields on button click
            //do it here.
        }
    
            //Unless you want to reset them regarless of the validity
            //of the page. Then do it here.
    }