Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5

Thread: Date validation

  1. #1
    New Coder
    Join Date
    Dec 2013
    Posts
    14
    Thanks
    1
    Thanked 1 Time in 1 Post

    Date validation

    Hi there all,

    I have been struggling with validating a date. The user enters a date into a text input. I want to check it is a valid date in dd/mm/yyyy or dd-mm-yyyy format, I also want to make sure its a date in the future. At the moment it doesn't seem to accept a valid date and I have no idea why. If anyone could help I would be eternally appreciative. the function is called as part of a larger function when the form is submitted. my javascript code is as follows:
    Code:
    function dateCheck() {
            var dateInput = document.getElementById('cDate').value;
            var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
            var today = new Date();
    
            if (dateFormat.test(dateInput) === true) {
                if (dateInput.indexOf("/") > 0) {
                    var splitDate = dateInput.split("/");
                } else {
                    var splitDate = dateInput.split("-");
                }
                var dateEntered = new Date(splitDate[2], splitDate[1], splitDate[0]);
                if ((dateEntered.getDate() == splitDate[0]) && (dateEntered.getMonth()  == splitDate[1]) && (dateEntered.getFullYear() == splitDate[2])) {
                    if (dateCheck > today) {
                        return true;
                    } else {
                        producePrompt("Date in past", "datePrompt", "red");
                        return false;
                    }
                } else {
                    producePrompt("Invalid Date", "datePrompt", "red");
                    return false;
                }
            } else {
                producePrompt("Invalid Date Format", "datePrompt", "red");
                return false;
            }
        }

  • #2
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    A simple date format is sufficient.
    Code:
    <body>
    <p><input type="text" id="npt" onblur="tstDte(this.value)">&nbsp;Enter a date dd/mm/yyyy or dd.mm.yyyy</p>
    
    <script type="text/javascript">
    
    function tstDte(val){var dte,mnt,tdy=new Date(),dateFormat=/(\d\d)\D+(\d\d)\D+(\d\d\d\d)/;
    	
    	val.replace(dateFormat,function(a,d,m,y){dte=new Date(y,m-1,d);mnt=m-1});
    	
    	if (typeof(dte)!="object" || 0<tdy.valueOf()-dte.valueOf() || dte.getMonth()!=mnt) alert('No valid Date !')
    	else alert('Valid date !')
    }
    </script>
    </body>
    We use the methode replace (See this Mdn page) not to replace but only to define the new date dte and the entry javascript month mnt.

    1/ - Then if the format dd mm yyyy is not valid (with any separator - we allow, for example, one or more spaces) dte is not an object.
    2/ - We compare the values to test the new date is in the future.
    3/ - We compare the dte month with the entry month mnt which change if the date is not a valid date (29 02 2014 => 01 03 2014 or 31 04 2014 => 01 05 2014).

    NB: It's too possible to build a regular expression which test only digits with leading zeros or digits, with or without leading zeros, but with any separators. In fact, leading zeros and separators are nonsense !

    EDIT :
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="PSPad editor, www.pspad.com">
    <title></title>
    <style type="text/css">
    body {font-family:Georgia;background:#ccc;}
    #pge {width:300px;margin:30px auto;padding:13px;background:#ffc}
    p {margin:3px auto;text-align:center;}
    input {text-align:center}
    #rsp {color:#f00}
    </style>
    </head>
    <body>
    <div id="pge"><fieldset><legend>Date validation (month date year)</legend>
    	<p>&nbsp;<br><input id="dte" type="txt" value="New year 1 1 2014">&nbsp;<a href="#" onclick=tst()>Ok !</a><br><br>
    	Form for dates (and others caracters)<br> with separators or leading zéros</p>
    	<p id="rsp">&nbsp;</p>
    </fieldset></div>
    <script type="text/javascript">
    function tst(){
     	var str=document.getElementById('dte').value, mth, dte;
    	var rgx=/(\d(?=\D)|\d\d)[\D]*(\d(?=\D)|\d\d)[\D]*([1-9][0-9]{3})/;
    	str.replace(rgx,
    		function(allPat,m,d,y){mnt=m-1;dte=new Date(y,mnt,d);});
    	var rsp=document.getElementById('rsp');
    	if (typeof(dte)!='object' || mnt!=dte.getMonth()) {rsp.innerHTML='Enter a valid date with separators or leading zeros mmjjyyyy';return}
    	else rsp.innerHTML=dte.toLocaleString();
    	return false;
    }
    </script>
    </body>
    </html>
    Last edited by 007julien; 02-10-2014 at 10:37 AM. Reason: complement

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,461
    Thanks
    11
    Thanked 600 Times in 580 Posts
    it would help to use an input type=date instead of text, which will make the specific formatting less of an issue for users with browsers that support it. Leep in mind that not everyone expect to put the month before the day in their culture. You still do whatever you're doing now at the same time you're doing it now, but this adds a nicer data-entry widget and ensures that a consistent date format gets passed to the validation function. The 'date' input type also supports the 'min' attrib, which you can set to Date() upon load to ensure a future date is selected, regardless of the user's timezone.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    Code:
    ENTER DATE (UK FORMAT DD/MM/YYYY) <input type = "text" id = "dateIn" onblur = checkValidDate(this.value)>
    
    <script type = "text/javascript">
    
    // Is the date valid?
    
    function checkValidDate(which) {
    which = which.replace(/[-:,\.]/g,"/");  // change delimiters to /
    which = which.replace(/[^0-9\/]/,"");  // strip non-digits
    var dt = which.split("/");
    var yr = dt[2];
    if (!yr) {yr = 9999}
    if (yr.length == 2) {yr = Number(yr) + 2000}
    if ((yr < 1900) || ( yr > 2100)) {
    alert ("Invalid Year!");
    document.getElementById("dateIn").value = "";
    return false;
    }
    var mm = dt[1]-1;  // in Javascript months are 0-11
    var mmx = dt[1];
    var dd = dt[0];  // day
    var nd = new Date();
    nd.setFullYear(yr,mm,dd);  // YYYY,MM(0-11),DD
    var ndmm = nd.getMonth();
    if (ndmm != mm) {
    alert (dd + "/" + mmx + "/" + yr  + " is an Invalid Date!");
    document.getElementById("dateIn").value = "";
    return false; 
    }
    else {
    alert (dd + "/" + mmx + "/" + yr  + " is an Valid Date!");
    }
    
    // Is the date today or after?
    
    var today = new Date();
    if (nd < today) {  // change to if (nd <= today) { if date must be after today
    alert ("Date must be today or after!");
    document.getElementById("dateIn").value = "";
    return false;
    }
    
    
    }
    
    </script>
    Last edited by Philip M; 02-12-2014 at 10:30 AM. Reason: Correction

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    a variant with a more efficient condition (thanks to the comma operator).
    Code:
    <body>
    <div id="pge"><fieldset><legend>Date validation (month date year)</legend>
    	<p>&nbsp;<br><input id="dte" type="txt" value="New year 1 1 2014">&nbsp;<a href="#" onclick="tst()">Ok !</a><br><br>
    	Form for dates (and others caracters)<br> with separators or leading zéros</p>
    	<p id="rsp">&nbsp;</p>
    </fieldset></div>
    <script type="text/javascript">
    function tst(){
     	var str=document.getElementById('dte').value, mth, dte;
    	var rgx=/(\d(?=\D)|\d\d)[\D]*(\d(?=\D)|\d\d)[\D]*([1-9][0-9]{3})/;
    	str.replace(rgx,
    		function(allPat,m,d,y){mnt=m-1;dte=new Date(y,mnt,d);});
    	var msg,rsp=document.getElementById('rsp');
    	if (		(msg="No valid Formet !",typeof(dte)!='object')
    			|| (msg="No valid Date !",mnt!=dte.getMonth())
    			|| (msg="Not a furture Date !",dte.valueOf()<new Date().valueOf())
    			|| (msg=dte.toLocaleString())) rsp.innerHTML=msg;
    	return false;
    }
    </script>
    </body>


  •  

    Posting Permissions

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