Geekpedia Forums Logo

javascript datetime validation

by venkatesh padmanabhan on Friday, November 30th - 12:55 AM



Hi..

I have a javascript datetime picker calendar and a textbox in my web application. The user selects the datetime picker and uses the tab continuously. so at one point of time, there is no focus on the calender pick. Then the user clicks the enter button. The data which appears in the textbox is like this at this point of time: /11/2007 11:12:59

As you can see, the date is not present(only the month,year and the time is present).. I want to validate this.

How to check if the date time entered in the textbox is in proper format through javascript?

Please help

Hi,

There is no inbuilt method to check the date time format in Java script, So if you want to validate the date , you have to write the complete Java script code using substring function, comparison operator etc. Or you can validate the date on server side which is fairly simple.

Thanks
Vivek

It looks like I'm pretty late on this, but the original answer is actually incorrect.  Javascript supports regular expressions, which can be used for this sort of thing to check the structure of the date supplied.

Here's an example of regex validation on a 5-digit postal code:

function checkpostal(){
var re5digit=/^\d{5}$/ //regular expression defining a 5 digit number
if (document.myform.myinput.value.search(re5digit)==-1) //if match failed
alert("Please enter a valid 5 digit number inside form")
}
Source: http://www.javascriptkit.com/javatutors/re.shtml

A bit of web searching should yield a regex pattern appropriate for your date validation.  If you have a unique case or otherwise want to write your own, there are plenty of resources out there for regular expressions, and a number of tools that can make writing them easier.