I am trying to validate if the date is valid meaning that its not in the future and also make sure its a legit date i.e 03/32/2012 is not valid. What I currently have works only to verify if the date is valid but it does not work when I place the date in future. Also I am having a problem if someone enters a date like 03/32/2012 it will say that its not valid but they can still click save button and then the exception will occur. What is the best way to approach this.
Here is my code:
<asp:TextBox ID="tbDate" runat="server" Text=""></asp:TextBox>
<asp:Image ID="imgCalendar" runat="server" ImageUrl="~/App_Themes/Sugar2006/images/Calendar_scheduleHS.png" ImageAlign="Middle" />
<asp:CalendarExtender ID="ce" runat="server" TargetControlID ="tbDate" PopupButtonID="imgCalendar" />
<asp:MaskedEditExtender ID="mex" runat="server"
TargetControlID="tbDate"
Mask="99/99/9999"
MaskType="Date"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError" />
<asp:MaskedEditValidator ID="mev" runat="server"
ControlToValidate="tbDate"
ControlExtender="mex"
Display="Dynamic"
InvalidValueMessage="This date is invalid!" Font-Bold="True"
ForeColor="#D50000" />
<asp:RequiredFieldValidator runat="server" ID="DReq"
ControlToValidate="tbDate"
Display="None"
ErrorMessage="A Date is required." ValidationGroup="vgMyGroup"/>
<asp:ValidatorCalloutExtender runat="Server" ID="DReqE"
TargetControlID="DReq"
HighlightCssClass="validatorCalloutHighlight" />
I have set the ValidationGroup
on the MaskedEditValidator
and that fixed my issue. Also to fix to not allow future dates I have done the following inside the .cs file. All my issues have been resolved. Thanks. :)
protected void mev_Init(object sender, EventArgs e) {
((MaskedEditValidator)sender).MaximumValue = DateTime.Now.ToString("MM/dd/yyyy");
}
You can also use the CustomValidator and point ClientValidationFunction
to a custom javascript function.
Such a function would look like±
function validateField(source, args){ args.IsValid = true; }
In javascript you can use the following to check if a date is valid±
var timestamp = Date.parse(textBoxValue)
if (isNaN(timestamp)==false)
{
var d = new Date(timestamp);
}
You can then compare d
to the current date to check if it is in the future.