Skip to content

Checking Password and New Password text using CustomValidator

February 14, 2013

A useful tip for displaying error messages with your own customised error checking to be passed into the ValidationSummary component is the CustomValidator. As an example for comparing two text boxes that the password and re-entered passwords are the same. You can create the following asp.net CustomValidator :-

<asp:CustomValidator ID=”cfvPasswordsDoNotMatch” runat=”server”
                ErrorMessage=”Passwords do not match.” ValidationGroup=”CheckGroup” OnServerValidate=”cfvPasswordsDoNotMatch_ServerValidate”>
                *</asp:CustomValidator>

In the code behind you can then write the method: –

    protected void cfvDateCompare_ServerValidate(object source, ServerValidateEventArgs args)
    {
        pnlMessage.Visible = false;

        System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
        provider = new System.Globalization.CultureInfo(“en-GB”);

        DateTime StartTime;
        DateTime EndTime;

        if (txtStartTime.Text.Trim() != “”)
        {
            StartTime = Convert.ToDateTime(txtStartTime.Text.Trim(), provider);
        }
        else
        {
            StartTime = Convert.ToDateTime(DateTime.MaxValue);
        }

        if (txtEndTime.Text.Trim() != “”)
        {
            EndTime = Convert.ToDateTime(txtEndTime.Text.Trim(), provider);
        }
        else
        {
            EndTime = Convert.ToDateTime(DateTime.MinValue);
        }

        int result = DateTime.Compare(StartTime, EndTime);

        if (result <= 0)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }

Notice here that if the two text boxes match, then the validation is passed with the line args.IsValid = true

Then in the if (Page.IsValid) section, you can then write the code once the passwords match.

Do also bear in mind that your ValidationSummary ValidationGroup has to be CheckGroup, or you can remove this and have the ValidationGroup=””

Hope that helps!

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: