logo

Date validation on global servers

Are you creating databases that live on servers all around the world and worried that you don't know which format the server expects dates to be entered in to fields of the date/time data type?

You can use this method to be sure that dates get validated to the correct format, mm/dd/yyyy or dd/mm/yyyy depending on the settings of the server you are using.

First thing to do is find out which format the server uses. We can do this with a simple @Formula like the one below:

DateText:=@Text(@Date(2000; 12; 31); "D0S0");
Replace := "31" : "12" : "2000";
With := "dd" : "mm" : "yyyy";
@ReplaceSubstring(DateText; Replace; With)


This creates a reference to my New Year's Eve, year 2000, in text format and then replaces the day with dd, the month with mm and the year with yyyy. It can do this as it knows that where the 31 appears in the date string is the day part and the where the 12 appears is the month. The trick is that, with domino, this formula is computed on the server so the format is independent of the client's location.

The best way to use this code is to place it in a "hidden" computed for display text field called DateFormat that is on all your forms. JavaScript can then get the value of this whenever it needs to validate a date field.

Image

Notice in the technique used above the HTML for the field is generated explicitly*.

We now have a dynamic value on every form accessible to JavaScript. On this site (hosted in America) the code generated is:


<input name="DateFormat" value="mm/dd/yyyy" type="hidden">


Now we need to create the JavaScript that is going to use it. The following function returns true or false depending on whether or not the value of the field object passed to it matches the pattern of the format passed to it:

function ValiDate(obj, format){
dateBits = DateComponents(obj.value, format);
if (dateBits == null) return false;

day = dateBits[0];
month = dateBits[1];
year = dateBits[2];

if ((month < 1 || month > 12) || (day < 1 || day > 31)) { // check month range
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
return false;
}
if (month == 2) {
// check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
return false;
}
}
return true;
}


The next function needed, as it is called during the above function, is used to split the format string in to an array that lets the validation routine know the numeric value of day, month and year:

function DateComponents(dateStr, format) {
var results = new Array();
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat);

if (matchArray == null) return null;
// parse date into variables
if (format.charAt(0)=="d"){ //format=dd/mm
results[0] = matchArray[1];
results[1] = matchArray[3];
} else {
results[1] = matchArray[1];
results[0] = matchArray[3]; }
results[2] = matchArray[4];
return results;
}


So, whenever you need to make sure a field has a valid date entered, you just need to call the ValiDate function (notice the play on words!). For example, a Date of Birth field (dob) like the one below. Notice that, in order to help the user there is a Computed Text hotspot next to the field that diplays the format that is required.

Image

You can validate the entry however and whenever you like. For example, the onChange event could be set to alert the user to invlaid dates, as below, or the form's onSubmit event.

alert( (ValiDate( document.forms[0].dob, document.forms[0].DateFormat.value) ? 'Date is OK!' : 'Date is BAD!');

Test it here:
(format=mm/dd/yyyy)


Note: You can see all these techniques being used in my JavaScript Form Validator database. Beware though, this is not a simple database and, although it will take a lot to figure out what is going on, I think it is worth it ....

*This could be achieved simply by entering "type=\"hidden\"" in the HTML Attributes but this technique is worth demonstratin as it can come in useful every now and then. Read this document if you want to know why it is so useful.

Feedback

  1. improvement - support for "dd.mm.yyyy"

    Add folowing line at the beginning of DateComponents(): dateStr = (dateStr.indexOf(".") != 0) ? dateStr.replace(".", "/").replace(".", "/") : dateStr;

    1. Compute the date separator

      You can always compute the server date separator.

      Borrowing some of Jakes fromula code ;)

      Create a computed field called DateSep with the formula DateText:=@Text(@Date(2000; 12; 31); "D0S0"); Replace := "31" : "12" : "2000"; @SubSet(@Trim(@ReplaceSubstring(DateText; Replace; ""));1)

      Use this value in your Javascript were necessary.

      Or calculate the client side date separator using

      .toLocaleString()

      Info -> http://msdn.microsoft.com/scripting/default.htm?/scripting/jscript/doc/jsmthtolo calestring.htm

    2. Simpler - support for "dd.mm.yyyy"

      You don't need an additional line: Just add "\." in the second line of DateComponents().

      So, use "var datePat = /^(\d{1,2})(\/|-\.)(\d{1,2})\2(\d{2}|\d{4})$/;" instead of "var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;".

      Regards - Ralf

  2. It doesn't work for me, need help

    maybe i'm doing it wrong, o maybe the scrip has an error, can anybody help me?, I hope you read this comment.

    thanks!

  3. valiDate - and yyyy-mm-dd

    Hi Jake, great work, but I have a small request on the valiDate function.

    When a client uses Swedish dateformat ("yyyy-mm-dd") valiDate fails. Could you please offer an example as to solve this using your functions dateComponents and valiDate in the Form Validator R2.0 database?

    best regards Ib Johansen

      • avatar
      • Jake Howlett
      • Thu 16 Oct 2003

      Re: valiDate - and yyyy-mm-dd

      Ib,

      The key to the format of the date is in the regular expression. For standard format mm/dd/yyyy is is:

      var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

      For your yyyy-mm-dd format you need to edit this to match them the other way round. You will also need to change way the results[] array is populated so it gets the right values in the right places.

      I would help more but I am quite busy. Also, it's important that you learn what's going on in the code for yourself, as I'm sure you'll appreciate.

      If I get more time soon I will try and get round to changing the code to cater for other formats and post a response here.

      Jake

      Show the rest of this thread

      • avatar
      • joseph otieno
      • Thu 21 Jan 2010

      HI

      Please help me with the format of yyyy-mm-dd because i try many time but were not work out. HAPPY NEW YEAR.

    • avatar
    • Bill
    • Fri 17 Dec 2004

    Formula for DateFormat?

    What tool is being used to create a formula for the DateFormat hidden field? I've never seen the tool shown in the partial screenshot where you enter the formula. Presumably, programming in asp.net, I can come up with a formula in c# and use inline code to create DateFormat's value.

      • avatar
      • Jake
      • Fri 17 Dec 2004

      Re: Formula for DateFormat?

      Bill. The tool you've never seen before is Lotus Notes, you lucky man.

      This is a Lotus-based site. Sorry I can't help.

      Show the rest of this thread

  4. how ro validate the range(date) in php using javas

    hello sir i did validate for the date field and now i want to validate the range(i.e.the day is 1-31 and the month is 12 and the year) how to i validate..

    this is my code... var re2= /^\d{4}\/\d{2}\/\d{2}$/ if (!re2.test(dob.value)) { alert("Error:Date format must contain yyyy/mm/dd"); dob.focus(); return false; } return true;

    then how i validate the range for the date field..

      • avatar
      • Jake Howlett
      • Mon 24 Oct 2005

      Re: how ro validate the range(date) in php using j

      This might help: http://www.codestore.net/store.nsf/unid/DFOU-4PRG6R?OpenDocument

  5. Test Link broken??

    Clicking on the test-Link seems to be broken.. I only get Error on page..

      • avatar
      • Jake Howlett
      • Thu 25 Sep 2008

      Re: Test Link broken??

      Thanks Gerald. The form was missing. Fixed now.

    • avatar
    • parthiban
    • Fri 30 Apr 2010

    Please clearly explain me how to use date format (yyyy-mm-dd) in javascript using PHP.... and please tell in feb month many date not selected above date 29.... please alert that date format....

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:



Navigate other articles in the category "JavaScript"

« Previous Article Next Article »
Managing JavaScript "popup" windows   Using the void operator in anchor links

About This Article

Author: Jake Howlett
Category: JavaScript
Hat Tip: Jim Fricker
Keywords: Date; Format;

Options

Feedback
Print Friendly

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »