Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: validate date format (y/m/d)

  1. #1
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default validate date format (y/m/d)

    hi all

    i want to use a function to format date in (yyyy/mm/dd).
    The function is in my below code. how can i call this function onChange or onBlur so that when the user enters date it should alert if the date format is not valid.

    Code:
    <html>
    <head>
    <script language="javascript">
    function validDate(y,m,d) 
    {
    if (y != parseInt(y,10) || m != parseInt(m,10)
    || d != parseInt(d,10)) return false;
    m--;
    var nd = new Date(y, m, d);
    if (y == nd.getFullYear() && m == nd.getMonth()
    && d == nd.getDate()) return nd;
    else return false;
    } 
    var customer_dob = validDate(year, month, day);
    if (!customer_dob) 
    {
    alert('the date entered is invalid');
    }
    </script>
    </head>
    <body>
    <form action="" method="get" name="advertise">
    <input type="text" name="customer_dob" onChange="return validDate();" />
    </form>
    </body>
    Last edited by vineet; 12-10-2008 at 01:57 PM. Reason: resolved

  2. #2
    Join Date
    Oct 2008
    Location
    Sweden
    Posts
    2,023
    Thanks
    17
    Thanked 319 Times in 318 Posts
    Blog Entries
    3

    Default

    I found a script and rewrote it a bit to fit your requirements. It is a bit more advanced since it checks for leap years (even checks if they are divisible by 400). Here is the code:

    HTML Code:
    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script language = "Javascript">
    /**
     * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
     */
    // Declaring valid date character, minimum year and maximum year
    // Changed by Snookerman into yyyy/mm/dd format
    var dtCh= "/";
    var minYear=1900;
    var maxYear=2100;
    
    function isInteger(s){
    	var i;
        for (i = 0; i < s.length; i++){   
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        // All characters are numbers.
        return true;
    }
    
    function stripCharsInBag(s, bag){
    	var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++){   
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }
    
    function daysInFebruary (year){
    	// February has 29 days in any year evenly divisible by four,
        // EXCEPT for centurial years which are not also divisible by 400.
        return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
    }
    function DaysArray(n) {
    	for (var i = 1; i <= n; i++) {
    		this[i] = 31
    		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
    		if (i==2) {this[i] = 29}
       } 
       return this
    }
    
    function isDate(dtStr){
    	var daysInMonth = DaysArray(12)
    	var pos1=dtStr.indexOf(dtCh)
    	var pos2=dtStr.indexOf(dtCh,pos1+1)
    	var strYear=dtStr.substring(0,pos1)
    	var strMonth=dtStr.substring(pos1+1,pos2)
    	var strDay=dtStr.substring(pos2+1)
    	strYr=strYear
    	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    	for (var i = 1; i <= 3; i++) {
    		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    	}
    	month=parseInt(strMonth)
    	day=parseInt(strDay)
    	year=parseInt(strYr)
    	if (pos1==-1 || pos2==-1){
    		alert("The date format should be : yyyy/mm/dd")
    		return false
    	}
    	if (strMonth.length<1 || month<1 || month>12){
    		alert("Please enter a valid month")
    		return false
    	}
    	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    		alert("Please enter a valid day")
    		return false
    	}
    	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
    		return false
    	}
    	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
    		alert("Please enter a valid date")
    		return false
    	}
    return true
    }
    
    function ValidateForm(){
    	var dt=document.frmSample.txtDate
    	if (isDate(dt.value)==false){
    		dt.focus()
    		return false
    	}
        return true
     }
    
    </script>
    </head>
    <body>
    <form name="frmSample" method="post" action="" onSubmit="return ValidateForm()">
      <p>Enter a Date <font color="#CC0000"><b>(yyyy/mm/dd)</b></font> :
        <input type="text" name="txtDate" maxlength="10" size="15">
      </p>
      <p>
        <input type="submit" name="Submit" value="Submit">
      </p>
    </form>
    </body>
    </html>
    The original code is taken from here:

    http://www.smartwebby.com/DHTML/date_validation.asp

    I just changed it to your format, yyyy/mm/dd.

  3. #3
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default date validation

    hi Snookerman

    thanks a lot. it worked great. its really advanced script.

    vineet

  4. #4
    Join Date
    Oct 2008
    Location
    Sweden
    Posts
    2,023
    Thanks
    17
    Thanked 319 Times in 318 Posts
    Blog Entries
    3

    Default

    You're welcome! Make sure you mark this thread as Resolved.

  5. #5
    Join Date
    Jul 2006
    Location
    just north of Boston, MA
    Posts
    1,806
    Thanks
    13
    Thanked 72 Times in 72 Posts

    Default

    If you wanted just to check whether the date was entered in a valid format, you could use the following

    Code:
    <script type="javascript">
    function checkDateFormat(field)
    {
         /* What will be separating the values */
         var delimiter="/";
         /* Message to display if date format is incorrect */
         var msg = "The date you entered, appears to be in an incorrect format.";
    
         /********************************
         **   no need to edit beyond this line      **
         ********************************/
         var el = document.getElementById(field);
    
         /* checks if delimiter is regexp "wildcard" */
         if(/[-./].test(delimiter))
              delimiter = "\"+delimiter; 
    
         /* yyyy(delimiter)mm(delimiter)dd */
         var format = "/^[(19)|(20)]\d{2}"+delimiter+"[0-3]?[0-9]"+delimiter+"[0-3]?[0-9]$/";
    
         /* if error message already exists */
         var errMsg = document.getElementById('errMsg');
         if(errMsg);
             el.removeChild(errMsg);
    
         /* if doesn't follow format, writes error message */
         if(!format.test(el))
         {
              var p = document.createElement('p');
              p.id="errMsg";
              p.style.color = "#ff0000";
              p.style.font-weight = "bold";
              p.nodeValue = msg;
              el.appendChild(p);
         }
    }
    </script>
    Code:
    <input type="text" name="f_date" value="" onchange="javascript:checkDateFormat(this);">
    If entered incorrectly, will produce the following with the example message
    The date you entered, appears to be in an incorrect format.
    Last edited by boogyman; 12-10-2008 at 05:27 PM. Reason: add error message validation

  6. #6
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default date format

    hi boogyman

    i think something is missing in your code.

    i pasted it and half of the script is coming in original javascript code color and rest bottom half is coming in single blue colour.

    vineet

  7. #7
    Join Date
    Jul 2006
    Location
    just north of Boston, MA
    Posts
    1,806
    Thanks
    13
    Thanked 72 Times in 72 Posts

    Default

    change

    delimiter = "\"+delimiter;
    to

    Code:
    delimiter = "\\"+delimiter;
    the first backslash was escaping the end quotation

  8. #8
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default date format

    hi boogyman

    This is complete code with correction which is giving error.
    Code:
    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script language="javascript">
    function checkDateFormat(field,delimiter)
    {
         /* What will be separating the values */
         var delimiter="/";
         /* Message to display if date format is incorrect */
         var msg = "The date you entered, appears to be in an incorrect format.";
    
         /********************************
         **   no need to edit beyond this line      **
         ********************************/
         var el = document.getElementById(field);
    
         /* checks if delimiter is regexp "wildcard" */
         if(/[-./].test(delimiter))
             delimiter = "\\"+delimiter;
        
         var format = "/^[(19)|(20)]\d{2}"+delimiter+"[0-3]?[0-9]"+delimiter+"[0-3]?[0-9]$/";
    
         if(!format.test(el))
         {
              var p = document.createElement('p');
              p.style.color = "#ff0000";
              p.style.font-weight = "bold";
              p.nodeValue = msg;
              el.appendChild(p);
         }
    }
    </script>
    </head>
    <body>
    <form name="form1" method="post" action="">
      <p>Enter a Date <font color="#CC0000"><b>(yyyy/mm/dd)</b></font> :
       <input type="text" name="f_date" value="" onchange="javascript:checkDateFormat(this);">
      </p>
      <p>
        <input type="submit" name="Submit" value="Submit">
      </p>
    </form>
    </body>
    </html>
    This is the error its giving
    Code:
    Line:20
    Char:31
    Error: Expected '/'
    Code:0
    its not alerting

    vineet

  9. #9
    Join Date
    Oct 2008
    Location
    Sweden
    Posts
    2,023
    Thanks
    17
    Thanked 319 Times in 318 Posts
    Blog Entries
    3

    Default

    Is the code I posted working for you?

  10. #10
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Snookerman View Post
    Is the code I posted working for you?
    hi snookerman

    yes the code you posted is working for me.

    i m just telling boogyman that his code has some errors.

    otherwise our issue has been resolved.

    vineet

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •