Question

Jscript date-time input mask validation

Asked by: andy7789

Hi X-perts,

I need a simple script to validate user's unput of date & time with some mask. It should check input of nymbers only and give a slash prompt, when input is correct.  have found a lot of scripts, but not exactly what I need. This script below check only date but not time:

<script>
function validDate(obj){
 date=obj.value
if (/[^\d/]|(\/\/)/g.test(date))  {obj.value=obj.value.replace(/[^\d/]/g,'');obj.value=obj.value.replace(/\/{2}/g,'/'); return }
if (/^\d{2}$/.test(date)){obj.value=obj.value+'/'; return }
if (/^\d{2}\/\d{2}$/.test(date)){obj.value=obj.value+'/'; return }
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(date)) return

 test1=(/^\d{1,2}\/?\d{1,2}\/\d{4}$/.test(date))
 date=date.split('/')
 d=new Date(date[2],date[1]-1,date[0])
 test2=(1*date[0]==d.getDate() && 1*date[1]==(d.getMonth()+1) && 1*date[2]==d.getFullYear())
 if (test1 && test2) return true
 alert("Invalid date")
 obj.select();
 obj.focus()
 return false
}
</script>
<body>
<p>Date1: <input type="text" name="startDate" size="9" maxLength="10"
onkeyup="validDate(this)"  onblur="validDate(this)"> </p>
</body>
</html>

What should be fixed to add time input to the same field in the form HH:MM (24h format)? Maybe someone has a better solution...

Thanks

Andy

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-05-26 at 01:49:59ID21864796
Tags

date

,

mask

,

input

,

time

Topic

JavaScript

Participating Experts
2
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Problem with onBlur and onKeyUp
    I am validating characters. I am sending the control to a function when it is onBlur and when it is onKeyUp. I need an error message to display if the character is entered....or if the user tries to leave the control with an invalid character. But if I use both of these event...
  2. Mask and Validate a DD/MM/YYYY DATE
    Hi. I saw many scripts that mask a field with a date mask, but it's not what i want. I want a function that uses a mask and a validate method together. Look at this example: First I type the number 3 3_/__/____ so...when I press the second key... with a number between 2 and 9...
  3. onChange and onKeyup
    Is there a problem with having an input that fires the same javascript function onchange and onkeyup? I am looking if there are any negatives to this also if so what the solution would be. The situation to be covered is that I have an input. When an ID is entered a functio...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mplungjanPosted on 2006-05-26 at 02:03:23ID: 16767515

How about not allowing them to enter an illegal date in the first place?

<html>
<head>
     <title>Untitled</title>
<script>
/* Set days in month script
   Copyright (c) 2003-2006 Michel Plungjan "javascripts (a) planet.nl" */
// Change the values below if needed:
adjustYears=true; // fix the year drop down to be around now.
yearAdjustment=-2; // how many years prior to this year
numberOfYears = 5; // how many years in the dropdown

function setDate(theForm) {
  var year = theForm.year.options[theForm.year.selectedIndex].value
  if (!year) return
  var month = theForm.month.options[theForm.month.selectedIndex].value
  if (!month) return
  var d = new Date(year,month,0); // last day in the previous month because months start on 0
  var daysInMonth = d.getDate();
  theForm.day.options.length=29;// save the minimum days
  if (daysInMonth>28) for (i=29;i<=daysInMonth;i++) {
    theForm.day.options.length++
    theForm.day.options[theForm.day.options.length-1] = new Option(i,i)
  }
}
function setNow() {
  var now = new Date()
  var ySel = document.forms[0].year;
  var mSel = document.forms[0].month;
  var dSel = document.forms[0].day;
  var hSel = document.forms[0].hour;
  var minSel = document.forms[0].min;

  var year = now.getFullYear();

  if (adjustYears) {
    var firstYear = year + yearAdjustment;
    ySel.options.length=1; // remove all but 1st option
    for (var i=firstYear, n=firstYear+numberOfYears;i<n;i++) {
      ySel.options.length++
      ySel.options[ySel.options.length-1] = new Option(i,i)
    }
  }
  var minYear = parseInt(ySel.options[1].value);
  var diff = year-minYear+1;
  ySel.selectedIndex=((diff)>0)?diff:0;

  mSel.selectedIndex = now.getMonth()+1;
  dSel.selectedIndex = now.getDate(); // NB: Not 0 based

  hSel.selectedIndex=now.getHours()+1;
  minSel.selectedIndex= now.getMinutes()+1;
}
</script>
</head>

<body onLoad="setNow()">
<form>
<select name="year" onChange="setDate(this.form)">
<option value="">Year
<option value="2003">2003
<option value="2004">2004
<option value="2005">2005
<option value="2006">2006
<option value="2007">2007
</select>
<select name="month" onChange="setDate(this.form)">
<option value="">Month
<option value="1">Jan
<option value="2">Feb
<option value="3">Mar
<option value="4">April
<option value="5">May
<option value="6">June
<option value="7">July
<option value="8">Aug
<option value="9">Sep
<option value="10">Oct
<option value="11">Nov
<option value="12">Dec
</select>
<select name="day"><!-- Use all days to help NS4 -->
<option value="">Day
<option value="1">1
<option value="2">2
<option value="3">3
<option value="4">4
<option value="5">5
<option value="6">6
<option value="7">7
<option value="8">8
<option value="9">9
<option value="10">10
<option value="11">11
<option value="12">12
<option value="13">13
<option value="14">14
<option value="15">15
<option value="16">16
<option value="17">17
<option value="18">18
<option value="19">19
<option value="20">20
<option value="21">21
<option value="22">22
<option value="23">23
<option value="24">24
<option value="25">25
<option value="26">26
<option value="27">27
<option value="28">28
<option value="29">29
<option value="30">30
<option value="31">31
</select>
<select name="hour">
<option value="">Hour
<option value="0">00
<option value="1">01
<option value="2">02
<option value="3">03
<option value="4">04
<option value="5">05
<option value="6">06
<option value="7">07
<option value="8">08
<option value="9">09
<option value="10">10
<option value="11">11
<option value="12">12
<option value="13">13
<option value="14">14
<option value="15">15
<option value="16">16
<option value="17">17
<option value="18">18
<option value="19">19
<option value="20">20
<option value="21">21
<option value="22">22
<option value="23">23
</select>:
<select name="min">
<option value="">min
<option value="0">00
<option value="1">01
<option value="2">02
<option value="3">03
<option value="4">04
<option value="5">05
<option value="6">06
<option value="7">07
<option value="8">08
<option value="9">09
<option value="10">10
<option value="11">11
<option value="12">12
<option value="13">13
<option value="14">14
<option value="15">15
<option value="16">16
<option value="17">17
<option value="18">18
<option value="19">19
<option value="20">20
<option value="21">21
<option value="22">22
<option value="23">23
<option value="24">24
<option value="25">25
<option value="26">26
<option value="27">27
<option value="28">28
<option value="29">29
<option value="30">30
<option value="31">31
<option value="32">32
<option value="33">33
<option value="34">34
<option value="35">35
<option value="36">36
<option value="37">37
<option value="38">38
<option value="39">39
<option value="40">40
<option value="41">41
<option value="42">42
<option value="43">43
<option value="44">44
<option value="45">45
<option value="46">46
<option value="47">47
<option value="48">48
<option value="49">49
<option value="50">50
<option value="51">51
<option value="52">52
<option value="53">53
<option value="54">54
<option value="55">55
<option value="56">56
<option value="57">57
<option value="58">58
<option value="59">59

</select>
</form>


</body>
</html>

 

by: andy7789Posted on 2006-05-26 at 02:14:20ID: 16767583

Thanks mplungjan

It is not exactly what I am thinking of. It has to be just a single typing field, but not a few dropdown menus. Obviously, it is a good idea to validate date and month upon input. The 1st script validates the whole string, not the date-month.

Andy

 

by: mplungjanPosted on 2006-05-26 at 02:15:58ID: 16767597

How does a valid date look like for you?

 

by: andy7789Posted on 2006-05-26 at 02:25:46ID: 16767682

If we forget about leap years we should have at least

1. date  - 30 or 31 days depending on a given month and 28 days for Feb
2. 1<= month<=12
3. year>=2006  

 

by: mplungjanPosted on 2006-05-26 at 02:35:39ID: 16767730

I mean, how does the string look like that the user MUST enter

 

by: pravinasarPosted on 2006-05-26 at 04:10:09ID: 16768114


function isDate(fld) {
   var value = fld.value;
   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
   var matchArray = value.match(datePat); // is the format ok?
   if (matchArray == null) {
             alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
             return false;
   }
   return true;
}

<!-- Accept the Date in mm/dd/yyyy or mm-dd-yyyy format -->
<p>Date1: <input type="text" name="startDate" size="9" maxLength="10"
onkeyup="validDate(this)"  onblur="isDate(this)"> </p>

<!--- Refer to my posts for usage examples -->

http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21860586.html

Following  has a formatTime functions

http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21851048.html

 

by: andy7789Posted on 2006-05-26 at 05:18:27ID: 16768455

mplungjan,

Sorry, it seems that my reply to your post is missing;) The input string should look like:

dd/mm/yyyy hh:mm or
dd-mm-yyyy hh:mm

After date or month input there should be an automatic slash prompt (like the mask in the 1st code). The script what I am looking for should not only validate the input, but act as a mask

Best,

Andy

 

by: mplungjanPosted on 2006-05-26 at 06:35:09ID: 16768921

What is "an automatic slash prompt"

 

by: mplungjanPosted on 2006-05-26 at 06:38:08ID: 16768950

Too bad this does not work 100% (due to annoying americanism)

<form>
<input type="text" size="50" onKeyUp="this.form.showDate.value=new Date(this.value)">
<br>
<input type="text" size="50" name="showDate">
</form>

 

by: andy7789Posted on 2006-06-01 at 16:08:45ID: 16812172

Thanks everybody for nice contributions. Finally, I had to rewrite my script based mostly on pravinasar solutions.
All the best
Andy

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...