SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard PHPycho's Avatar
    Join Date
    Dec 2005
    Posts
    1,200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JS date range validation ??

    I have two date field viz from-date and to-date
    and i want to validate that from-date should be less than or equal to to-date
    using javascript.
    Note: date field should be in yy-mm-dd format
    How is that possible ?
    Please help me..
    Thanks in advance..

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if the Date fields validate subtract their Date objects-

    if(new Date(from_date)-new Date(to_date)>0){
    throw new Error('Time travel is not allowed');
    }
    else// to_date is after from_date
    Last edited by mrhoo; Feb 22, 2007 at 21:30.

  3. #3
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    mrhoo's solution will not work for some users. Try this instead:
    Code:
    var from = "08-11-10";
    var to = "07-11-10";
    
    alert(isFirstEarlier(from, to));
    
    
    function isFirstEarlier(d1, d2)
    {
    	var d1pieces = d1.split("-");
    	var d2pieces = d2.split("-");
    	
    	var date1 = new Date(d1pieces[0], d1pieces[1], d1pieces[2]);
    	var date2 = new Date(d2pieces[0], d2pieces[1], d2pieces[2]);
    	
    	return date1 <= date2;  //compares milliseconds since the epoch
    }


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
  •