Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

validate date

Posted on 2009-02-21
13
Medium Priority
?
362 Views
Last Modified: 2012-08-14
i have been pounding my head on the wall......

how do you validate a date?

here is what i'm using for regex its working great but its failing when i enter "09/09/009"

here is the code:

 <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtStartDate"
                                        ValidationExpression="^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$"
                                        Text="*" ErrorMessage="Invalid Start Date" Display="Dynamic"></asp:RegularExpressionValidator>


i have the same question here but no help and none of those solution works for me

ps: please read my comments and also
if i enter "09/09/009"  the regex thinks its a valid date. actually its not.
0
Comment
Question by:nisarkhan
  • 6
  • 3
  • 3
  • +1
13 Comments
 
LVL 12

Expert Comment

by:CB_Thirumalai
ID: 23702880
Use this and you can get this validated for any date.
function fnEvaluateDate(obj){
	var bRetValue=true;
	if(obj.value!=""){
	    var dateObj=fnGetDateObj(obj);
	    var day=dateObj[2],month=dateObj[1],year=dateObj[0];
		var theDate=new Date(year,month-1,day);
	    if(theDate.getMonth()+1!=month || theDate.getDate()!=day || theDate.getFullYear()!=year)
	        bRetValue=false;
	}
	return bRetValue;
}
// Get Date Object (Always send object as {year,month,day})
function fnGetDateObj(obj){
    var retVal,actVal;
    switch(obj.dateType){
        case 'US':
            actVal=obj.value.split("/");
            retVal=new Array(actVal[2],actVal[0],actVal[1]);
            break;
    }
    return retVal;
}

Open in new window

0
 
LVL 7

Author Comment

by:nisarkhan
ID: 23702929
very frustration with date validation

is that client validation? can you please show me how i will be wiring?
thanks.
0
 
LVL 27

Expert Comment

by:nmarun
ID: 23702968
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 27

Expert Comment

by:nmarun
ID: 23702975
That'll make sure a user enters only in date format.
0
 
LVL 12

Expert Comment

by:CB_Thirumalai
ID: 23703077
Just have to put this in the onblur of the textbox that holds the date.  For example
If you textbox is as,
       <asp:Textbox ID="txtDate" runat="server"></asp:Textbox> then
In the page_load use an attribute.add as,
      txtDate.Attributes.Add("dateType", "US");
      txtDate.Attributes.Add("onblur", "if(!fnEvaluateDate(this))this.focus();"

If you want to use any different format, then just add the format in the fnGetDateObj function above as I did for US and the value of the add attribute dateType should be that value.  Hope this helps
0
 
LVL 7

Author Comment

by:nisarkhan
ID: 23703221
nmarun:: no third party tool

CB_Thirumalai:: i tried to use your code but does not work
here is the what i'm doing.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">
    
    function fnEvaluateDate(obj){
	var bRetValue=true;
	if(obj.value!=""){
	    var dateObj=fnGetDateObj(obj);
	    var day=dateObj[2],month=dateObj[1],year=dateObj[0];
		var theDate=new Date(year,month-1,day);
	    if(theDate.getMonth()+1!=month || theDate.getDate()!=day || theDate.getFullYear()!=year)
	        bRetValue=false;
	}
	return bRetValue;
}
// Get Date Object (Always send object as {year,month,day})
function fnGetDateObj(obj){
    var retVal,actVal;
    switch(obj.dateType){
        case 'US':
            actVal=obj.value.split("/");
            retVal=new Array(actVal[2],actVal[0],actVal[1]);
            break;
    }
    return retVal;
}
 
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Textbox ID="txtDate" runat="server"></asp:Textbox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" 
            ControlToValidate="txtDate" ErrorMessage="invalid date" 
            ClientValidationFunction="fnEvaluateDate" Display="Dynamic" 
            EnableTheming="True" SetFocusOnError="True"></asp:CustomValidator>
        <br />
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>
 
 
 protected void Page_Load(object sender, EventArgs e)
    {
         txtDate.Attributes.Add("dateType", "US");
         txtDate.Attributes.Add("onblur", "if(!fnEvaluateDate(this))this.focus();");
 
    }

Open in new window

0
 
LVL 7

Author Comment

by:nisarkhan
ID: 23703253
i'm using MM/DD/YYYY date format
0
 
LVL 15

Expert Comment

by:Praveen Venu
ID: 23703851
use this regex

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}
0
 
LVL 27

Expert Comment

by:nmarun
ID: 23704861
How about the native Calendar control?
0
 
LVL 7

Author Comment

by:nisarkhan
ID: 23705601
PraveenVenu:

no luck and its very strange ... if i enter the date like "02/02/1989" i get * (star) next to the txtDate textbox but in reality this is a valid date, any idea what i'm doing wrong?
 <asp:TextBox runat='server' ID='txtDate' CssClass='formElementCal'></asp:TextBox>
 
<ajaxToolkit:CalendarExtender ID="cal_date" TargetControlID='txtDate' runat="server" EnableViewState="true"></ajaxToolkit:CalendarExtender>
 
<ajaxToolkit:MaskedEditExtender ID="MaskedEditExtender3" runat="server" TargetControlID="txtDate" Mask="99/99/9999" MessageValidatorTip="true" OnFocusCssClass="MaskedEditFocus" OnInvalidCssClass="MaskedEditError" MaskType="Date" DisplayMoney="Left" AcceptNegative="Left" /> 
                           
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtDate"
ValidationExpression="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"
Text="*" ErrorMessage="Invalid Visit End Date" Display="Dynamic"></asp:RegularExpressionValidator> 
                           
                                  
                               

Open in new window

0
 
LVL 7

Author Comment

by:nisarkhan
ID: 23705618
also if enter date like this:
21/54/5454
i get this error:

 String was not recognized as a valid DateTime.

should the RegularExpressionValidator validation catch ?
0
 
LVL 12

Accepted Solution

by:
CB_Thirumalai earned 375 total points
ID: 23707935
Hi nisarkhan,

Sorry for late response.  The implementation is correct.  Only thing the error is not getting displayed because of the CustomValidator control.  To use CustomValidator,
- you need to have a function with the signature FUNCTIONNAME(SOURCE,ARGS)
- it is always safe to have the same set of function in the server side too when using a client validate function.

So, it is your option to catch the error in client-side or server-side.  The function I gave is perfectly correct, but not to be used with CustomValidator.  You may wish to modify as below, two options are given

OPTION 1:
-------------
- Remove the Custom Validator Control.
- Modify the txtDate attribute add as,
  txtDate.Attributes.Add("onblur", "if(!fnEvaluateDate(this)){alert('Please enter valid Date!');this.focus();}");

OPTION 2:
-----------
- Remove the javascript functions I have given above.
- Use CheckForValidDate function I have given below.
- Remove the Custom Validator Control.
- Modify the txtDate attribute add as,
  txtDate.Attributes.Add("onblur", "CheckForValidDate(this)");

String.prototype.trim = new Function("return this.replace(/\\s+$|^\\s*/gi,'');");
function CheckForValidDate(obj){//Check for valid date
      //Check the date value
      if(obj.value.trim()!=""){
            if(isNaN(new Date(obj.value))){
                  alert("You entered a invalid date. \n\n Please enter a date in the form mm/dd/yy");
                  obj.value="";
                  obj.focus();
            }else{
                  var theDate = obj.value.trim();
                  var re = "";
                  var febM = /^([0]?[2])[/]+/;
                  var theleapYear = /^([0]?[2])[/]([0]?[1-9]|[1][0-9]|[2][0-9])[/]([2][0][0][0]|[2][0][0][4]|[0]{2}|[0][4]|[2][0][0][8]|[0][8]|[2][0][1][2]|[1]|[2])$/;
                  if(febM.test(theDate))
                  {
                        if(theleapYear.test(theDate))
                              re = /^([0]?[2])[/]([0]?[1-9]|[1][0-9]|[2][0-9])[/]([0-9]{4}|[0-9]{2})$/;                  
                        else// February -- to do; leap years
                              re = /^([0]?[2])[/]([0]?[1-9]|[1][0-9]|[2][0-8])[/]([0-9]{4}|[0-9]{2})$/;                  
                  }
                  else
                  {
                        var thirtyM = /^([0]?[4]|[6]|[9]|[1][1])[/]+/;
                        // thirty day months
                        if(thirtyM.test(theDate))
                               re = /^([0]?[4]|[6]|[9]|[1][1])[/]([0]?[1-9]|[1|2][0-9]|[3][0])[/]([0-9]{4}|[0-9]{2})$/;
                        else
                              // other months
                               re = /^([0]?[1-9]|[1][0-2])[/]([0]?[1-9]|[1|2][0-9]|[3][0|1])[/]([0-9]{4}|[0-9]{2})$/;
                  }
                  
                  if(!re.test(theDate)){
                        alert("You entered a invalid date. \n\n Please enter a date in the form mm/dd/yy or mm/dd/yyyy");
                        obj.value="";
                        obj.focus();
                  }
            }            
      }
}
0
 
LVL 7

Author Closing Comment

by:nisarkhan
ID: 31549691
i have not tested this solution, for the sake of closing this question i'm accepting this as answers
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses
Course of the Month21 days, 2 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question