views:

107

answers:

1

EDIT

Fixed the problem - I needed to add the validators to a ValidationGroup and then call each of the validation controls Validate() method on the submit behaviour of the button.

    protected void btnDone_Click(object sender, EventArgs e)
    {
        this.cvValidation.Validate();
        this.revYear.Validate();
        if (Page.IsValid)
        {
            DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));
            string str = sub.ToString("MMMM") + " " + sub.ToString("yyyy");
            pcePopUp.Commit(str);
        }
    }

I am trying to add a CustomValidator to my UserControl but I cannot get the validator to run as it should. What I am trying to achieve is to test to see if the month/year is in the future.

After breaking into the code I have noticed that the validateDate method is being fired twice. Any help on this situation would be greatly appreciated.

Could it be a problem with the way I am retrieving data from the controls as using the following two methods.

        private void loadPostBackData()
    {
        loadPostBackDataItem(((TextBox)puymcStartDate.FindControl("txtDate")));
        loadPostBackDataItem(((TextBox)puymcEndDate.FindControl("txtDate"))); 
    }

    private void loadPostBackDataItem(TextBox control)
    {
        string controlId = control.ClientID.Replace("_", "$");
        string postedValue = Request.Params[controlId];

        if (!String.IsNullOrEmpty(postedValue))
        {
            control.Text = postedValue;
        }
        else
        {
            control.Text = String.Empty;
        }
    }

UserControl code

ASP.NET Code

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CtrlPopUpYearMonthCalendar.ascx.cs" Inherits="CLIck10.Controls.CtrlPopUpYearMonthCalendar" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


        <asp:TextBox ID="txtDate" ReadOnly="true" runat="server" />

        <div id="divPopUp" runat="server" class="box" style="width:320px;visibility:hidden;margin-left:5px;">
            <div class="boxTitle">
                <h1>Choose date</h1>
            </div>
            <div style="padding:5px;">
                <asp:UpdatePanel id="upPopUp" UpdateMode="Always" runat="server">
                    <ContentTemplate>
                        <asp:DropDownList ID="ddlMonth" runat="server" /> <asp:TextBox ID="txtYear" runat="server" />
                        <asp:Button ID="btnDone" Text="Done" runat="server" UseSubmitBehavior="false" onclick="btnDone_Click" />
                        <asp:RegularExpressionValidator ID="revYear" ValidationExpression="^[0-9]{4}$" ControlToValidate="txtYear" Display="Dynamic" Text="(*)" ErrorMessage="Year must be valid" runat="server" />
                        <asp:CustomValidator ID="cvValidation" Text="(*)" Display="Dynamic" ErrorMessage="Date must be in the future" OnServerValidate="validateDate" ValidateEmptyText="true" runat="server" />
                        <asp:ValidationSummary ID="vsDate" runat="server" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>

<ajaxToolkit:PopupControlExtender ID="pcePopUp" PopupControlID="divPopUp" TargetControlID="txtDate" Position="Right" runat="server" />

Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Diagnostics;

namespace CLIck10.Controls
{
    public partial class CtrlPopUpYearMonthCalendar : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DateTime month = Convert.ToDateTime("01/01/2000");
                for (int i = 0; i < 12; i++)
                {
                    DateTime nextMonth = month.AddMonths(i);
                    ListItem item = new ListItem();
                    item.Text = nextMonth.ToString("MMMM");
                    item.Value = nextMonth.Month.ToString();
                    ddlMonth.Items.Add(item);
                }

                if (txtDate.Text.Equals(String.Empty))
                {
                    ddlMonth.Items.FindByValue(DateTime.Now.AddMonths(1).Month.ToString()).Selected = true;

                    if (DateTime.Now.Month.ToString("MM").Equals("12"))
                    {
                        txtYear.Text = DateTime.Now.AddYears(1).ToString("yyyy");
                    }
                    else
                    {
                        txtYear.Text = DateTime.Now.ToString("yyyy");
                    }
                }
                else
                {
                    DateTime date = Convert.ToDateTime("01, " + txtDate.Text);
                    ddlMonth.Items.FindByValue(date.Month.ToString()).Selected = true;
                    txtYear.Text = date.ToString("yyyy");
                } 
            }
        }

        protected void btnDone_Click(object sender, EventArgs e)
        {
            DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));
            string str = sub.ToString("MMMM") + " " + sub.ToString("yyyy");
            pcePopUp.Commit(str);
        }

        public void validateDate(object sender, ServerValidateEventArgs e)
        {
                DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));

                if (sub >= DateTime.Now)
                {
                    e.IsValid = true;
                }
                else
                {
                    e.IsValid = false;
                }
        }
    }
}

After experimenting with just embedding the control in a blank page It works so it must be something to do with the page I am working on.

+1  A: 

I tried out your code as a page (not a usercontrol) and it worked fine.

Are you dynamically adding your usercontrols to the page?

womp
The user controls are not being added dynamically. However I am getting the post data out of the controls using these two methods which are most likely what are causing the problems. http://tms.pastebin.com/m21627708http://tms.pastebin.com/m21627708
Malachi
I've wrapped the code within the button click event in a Page.IsValid conditional statement and that worked but still the validation method is firing twice.
Malachi