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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 27
  1. #1
    Regular Coder
    Join Date
    Oct 2010
    Posts
    127
    Thanks
    26
    Thanked 0 Times in 0 Posts

    Validating Date with JS using Reg Expression

    Hey all,

    I've been practicing JS and today I decided to create a "To Do" List.

    So far, I've gotten everything working properly except the validDate function which makes sure the date entered is in a valid format (12.12.2012 or 12/12/2012, etc.) However, it's not working in any browsers. I used Chrome Dev tools and I keep getting an error "addDueDate" is not defined. Any idea but I'm doing wrong. I'm very new to Reg Expressions so i very well could have messes something up.


    Code:
    <html>
    
    <head>
    <title>Untitled</title>
    </head>
    <body>
    <form name="list">
    <input type="text" name="datedue" value="Date Due" /> <br />
    <input type="text" name="todo" value="Task" /> <br />
    <input type="button" name="button1"  value="Submit" onclick="addList(); validDate()"/> <br />
    </form>
    <div id="todolist">
    <table>
    <tr>
    <td>Due Date </td>
    <td>Task</td>
    </tr>
    </table>
    </div>
    
    <script type="text/javascript">
    function addList () {
    var addDueDate=document.list.datedue.value;
    var addToList=document.list.todo.value;
    document.getElementById("todolist").innerHTML= "<table><tr><td> Due Date </td><td>Task</td></tr><tr><td>" + addDueDate + "</td><td> " + addToList +"</td></tr></table>";
    }
    
    
    var checkDateDue=document.list.datedue;
    var checkToDo= document.list.todo;
    
    checkDateDue.onfocus= function() {
    		if(checkDateDue.value=="Date Due") {
    		checkDateDue.value="";
    		}
    }
    checkToDo.onfocus= function() {
    	if(checkToDo.value=="Task") {
    	checkToDo.value="";
    	}
    }
    
    checkDateDue.onblur= function() {
    if (checkDateDue.value =="") {
    	alert("please enter the due date");
    	checkDateDue.value="Date Due";
    	}
    }	
    
    checkToDo.onblur=function() {
    if (checkToDo.value=="") {
    	 alert("Please enter your task");
    	 checkToDo.value="Task";
    }
    }
    
    function validDate() {
    var re= /^\d{2}[.\/-]\d{2[.\/-]\d{4}$/;
    if (re.test(addDueDate)== false) {
    	alert("please enter a valid date");
    }
    }
    </script>
    
    </html>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,537
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    The only place you have defined addDueDate is in this code:
    Code:
    function addList () {
        var addDueDate=document.list.datedue.value;
        var addToList=document.list.todo.value;
        document.getElementById("todolist").innerHTML= "<table><tr><td> Due Date </td><td>Task</td></tr><tr><td>" + addDueDate + "</td><td> " + addToList +"</td></tr></table>";
    }
    But that variable is FUNCTION SCOPE, meaning that as soon as the addList() function is finished running, that variable is gone into the ether. Zap. Non-existent.

    You could move the variable to global scope, but I think that's a bad idea.

    A little extra code isn't going to hurt, especially if it keeps intent clear:
    Code:
    function validDate() {
        var re= /^\d{2}[.\/-]\d{2[.\/-]\d{4}$/;
        if (re.test(document.list.datedue.value)== false) {
    	alert("please enter a valid date");
        }
    }
    NOW...there's another problem: You don't DO this validation until *AFTER* the item has ALREADY been "published" in the <table>. (And, by the by, it's bad practice to use innerHTML to generate an entier <table>, most experts would say.)

    So wouldn't it make more sense to simply incorporate the test into the the addList( ) function and then *NOT* publish to the <table> if the date is invalid?

    *NOW* you could simply do:
    Code:
    function addList () {
        var addDueDate=document.list.datedue.value;
        var re= /^\d{2}[.\/-]\d{2[.\/-]\d{4}$/;
        if ( ! re.test(addDueDate) ) {
    	alert("please enter a valid date");
            return;
        }
        var addToList=document.list.todo.value;
        document.getElementById("todolist").innerHTML= "<table><tr><td> Due Date </td><td>Task</td></tr><tr><td>" + addDueDate + "</td><td> " + addToList +"</td></tr></table>";
    }
    And get rid of your validDate() function and the call to it.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,537
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    Oh...and as another minor comment: Named <form>s are considered obsolete. You should give the <form> an id instead and use document.getElementById() to "find" the form. Of document.forms[0] and forget the id if you know you will only have one <form> on the page.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Regular Coder
    Join Date
    Oct 2010
    Posts
    127
    Thanks
    26
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    Oh...and as another minor comment: Named <form>s are considered obsolete. You should give the <form> an id instead and use document.getElementById() to "find" the form. Of document.forms[0] and forget the id if you know you will only have one <form> on the page.
    Thanks so much. All of this was very useful information. I will make the changes.

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    alert is for debugging only - you should display the error message in the web page itself.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,016
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Code:
    function validDate() {
    var re= /^\d{2}[.\/-]\d{2[.\/-]\d{4}$/;
    if (re.test(addDueDate)== false) {
    	alert("please enter a valid date");
    }
    }

    That checks if the format of the date is correct, (but note that USA and UK formats differ), but does not at all check whether the date is valid - not 56th February, or 26th of month 34, or year 9235. So not very useful.

    Code:
    <script type = "text/javascript">
    
    function checkValidDate(yr,mmx,dd) {
    
    if (yr <1910 || yr >2012) {  // you may want to change 2012 to some other year!
    alert ("Year is out of range")
    return false;
    }
    
    mm = mmx-1;  // remember that in Javascript date objects the months are 0-11
    var nd = new Date(yr,mm,dd);
    
    var ndmm = nd.getMonth();
    if (ndmm != mm) {
    alert (dd + "/" + mmx + "/" + yr  + " is an Invalid Date!");
    return false; 
    }
    else {
    alert (dd + "/" + mmx + "/" + yr  + " is a Valid Date");
    }
    }
    
    // USAGE:
    checkValidDate(2012,2,20)  // 20th February 2012  yyyy/mm/dd
    checkValidDate(2012,2,31)  // 31st February 2012  yyyy/mm/dd
    
    </script>
    As felgall says, alerts are used only for debugging/demonstration.
    Last edited by Philip M; 12-08-2012 at 07:59 AM.

    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.

  • #7
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    its a LOT less code, and a much better ux using HTML5:

    Code:
    <input 
     type="text" 
     name="datedue" 
     placeholder="Date Due"
     pattern="^[012]*\d{1}[.\/][0123]*\d{1}[.\/]\d{1,2}$"
     required
     />
    you can do the other js too, but this should be your html starting point.
    it works even with js disbled, and is more accessible than wresting with a script if you can't see everything at once, or at all for that matter...
    Last edited by rnd me; 12-08-2012 at 08:16 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,016
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    I have to say - while some 80% of browsers still in use do not support HTML5, stick with Javascript. I do accept that the new input types included in HTML5 will degrade properly in older browsers. But they do not actually work. And different browser vendors have implemented support in different ways. IE support seems to be minimal.

    And that pattern still does not check that the date is a valid one.

    But I have found a useful script to emulate HTML5 functionality:-
    https://github.com/ryanseddon/H5F
    Last edited by Philip M; 12-08-2012 at 08:58 AM.

    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.

  • #9
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by Philip M View Post
    I have to say - while some 80% of browsers still in use do not support HTML5, stick with Javascript.
    according to http://caniuse.com/#feat=form-validation, most users last month could expect the full validation set, and pattern is one of the most supported specific features of that.
    considering tablets are the #1 wish-list item this year, expect IE to take a big hit by the 31st. i expect the numbers for jan, when they come out in feb, will show at least 2/3 if not 3/4. let's hope!

    js should be used to provide graceful degradation.

    but the html5 costs almost nothing, and even right now runs works often than not, and works for those poor folks with javascript disabled we hear soo much about.

    i guess why code 5 lines when 20 will do right?


    i didn't go all out say simply use <input type=date>, that's crazy talk!
    Last edited by rnd me; 12-08-2012 at 09:19 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #10
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    FWIW I find the HTML5 form attributes look (and perhaps behave) differently in different browsers; I know this is to be expected but sometimes the difference is quite discernible. This is tempting me to ignore (most of) them, use JS, but (of course) rely on server-side validation.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,016
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Quote Originally Posted by AndrewGSW View Post
    FWIW I find the HTML5 form attributes look (and perhaps behave) differently in different browsers; I know this is to be expected but sometimes the difference is quite discernible. This is tempting me to ignore (most of) them, use JS, but (of course) rely on server-side validation.
    Once more, I agree totally with your comments.

    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.

  • #12
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    Regardless of the use of HTML5, I think it is unpleasant to impose a separator rather an other one, the choice should be left to the user. In addition, the user may prefer to use leading zeros...

    Then I propose this regular expression (without ^ at the beginning nor $ at the end, to authorize spaces or other words) :
    Code:
    var rgx=/(\d(?=\D)|\d\d)[\D]*(\d(?=\D)|\d\d)[\D]*([1-9][0-9]{3})/;
    It allows in particular :
    • One digit following by a separator or two digits,
    • Possibly one or some separator,
    • One digit following by a separator or two digits,
    • Possibly one or some separator,
    • Exactly 4 digits.

    To validate a date, it is still advisable to verify that this one exists (See the source of this test page).

  • #13
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Can't I just type two digits for the year
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #14
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by AndrewGSW
    FWIW I find the HTML5 form attributes look (and perhaps behave) differently in different browsers; I know this is to be expected but sometimes the difference is quite discernible. This is tempting me to ignore (most of) them, use JS, but (of course) rely on server-side validation.
    Quote Originally Posted by Philip M View Post
    Once more, I agree totally with your comments.
    i think it's time you guys had a second look.

    try it live at http://danml.com/formtest.html


    the following behaves exactly the same in ie, ff, ch, and op, i didn't test safari.

    furthermore, it's a much nicer ui, provides color-based real-time feedback, hooks directly into the accessible API used by A.T. to communicate requirements to the visually and physically disabled, won't let wrong info be submitted (even w/o js), doesn't use alert(), doesn't use hand-coded validation-error messages (less work each field), errors message appear in the local language, bad entries text can survive a page refresh for a 2nd chance to correct errors without retyping, and allows custom css to style the various validity states.


    Can your javascript do all that ?

    Code:
    <!DOCTYPE html><html>
    <head>
    	<title>html5 form test</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
      [id]:valid{ background:#cfc; }
      [id]:invalid{ background:#fcc; outline: 0; box-shadow: none; }
    </style>
    </head>
    <body>
      
      <h1>htm5 form validation test </h1>
    <form onsubmit="return false;">
    	<label for="datedue">
    		<b>Date Due</b>
    		<input type="text" name="datedue" id="datedue" placeholder="mm/dd/yy" title="mm/dd/yy"
    		 pattern="^[01]*\d{1}[.\/][0123]*\d{1}[.\/]\d{2,4}$" required autofocus
    		/>
    	</label>
    	<input type=submit />
    </form>
    
    </body>
    </html>

    again, i test in the top 4 browsers, and the behavior is nearly identical, and very nice UX i must say, in all of them.

    the only differences i noticed was the wording on the message, but it was all saying the same thing, and all of them correctly showed the title attrib as the suggestion:


    FF/CH:
    Code:
    Please match the requested format:
    mm/dd/yy
    OP:
    Code:
    Please use the required format:
    mm/dd/yy
    IE:
    Code:
    You must use this format:  mm/dd/yy


    step back from past experiences for a moment, try the code in your favorite browsers, and ask yourself "is all that really worth typing 3 attribs?"

    if you think not, and you would rather give your users a pop-up box that can leave them with no further communication if the check it's little checkbox, or you can have something that works almost everywhere, can easily be poly-filled for IE7/8, feels nice, behaves well, looks better, is highly accessible, and much less code to write for each app/field, then i suggest you take up photography or knitting or something besides web dev.


    if nothing else, rip your config from the html and feed that to javascript instead of hand-coding strings and one-language error message; i can't see the harm at all.
    Last edited by rnd me; 12-08-2012 at 08:38 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #15
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Just my opinion.. but a single input on a page doesn't convince. It's when trying to create an entire form on a page that the differences are more obvious.

    Even so, it looks noticeably different in IE and, in fact, the submit button (which displays "Submit Query" and is therefore much wider) did nothing for me at all in IE9; the input-background is not pink. FF17 says "Please fill out this field" - it doesn't include the "dd/mm/yy". Added I am aware that not all of these points are directly relevant to HTML5.

    Personally, I am not interested in debating the point - I'm just recounting my experience and thoughts. Besides, I am not rejecting HTML5 - I'm happy to use it where it is useful (autofocus, required..), but one cannot ignore the differences.
    Last edited by AndrewGSW; 12-08-2012 at 08:33 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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