site logo

Date validation

Date format entry depends on national conventions. In this article you find live form for European date entry [dd.mm.yyyy], JavaScript for entered date validation on client and AJAX script for date validation on server.

As valid date it is considered such entry, which both client script and server script evaluate as valid and after type cast to data type datetime and back to string is obtained the same date (no urgently in the same format). Using data type datetime is absolute necessity when date value is used for search, or calculation (number record for certain period, duration of downtime).

Test form and scripts

euro date browser server

Enter date into textbox of mini-form formated as [dd.mm.yyyy], by click on button test starts date validation. At first date is evaluated by JavaScript in browser, then is date is sended for validation to server by the help of Ajax.

JavaScript validation is done in style yes/no, server returns recast type of date, or error message.

Server validation is done by different function than JavaScript, and that is why results are not identical. For possibility to save data into database, definitive is server side validation. Server validation understand also month names instead of number. Because of Czech national environment of server, you can use Czech month names only. Try to enter date "1.13.2008", or "22 leden 1947". Other usable month names (without diacritic) are "srpen", "duben".

Client side validation by help of JavaScript follows.


<script type="text/javascript">
// ---------- validation on client by JavaScript -----------
function testDate() {
  var dtStr = document.getElementById("dtInp").value;
  if (checkDate(dtStr) == true)
    document.getElementById("testClient").innerHTML = "O.K.";
  else
    document.getElementById("testClient").innerHTML = "error";
}

function checkDateEU(value) {
  if(value == "") return false;
  var dtArr = value.split(".");
  if(dtArr.length != 3) return false;
  var dx = new Date(dtArr[2], dtArr[1]-1, dtArr[0]);
  if(dx.getDate() != dtArr[0]) return false;
  if(dx.getMonth()+1 != dtArr[1]) return false;
  return true;
}
</script>

The first function for checking date on client side is auxiliary function and here represents central validation function. Function retrieves form field value, calls common validation function and reports validation result.

The second function performs date validation in European format, and returns logical values true, or false according to result. At first step, date string is splitted according to delimiter character (here point) to array containing day, month, year. Values from array are used for creation of new object Date, which take into account number of days in varied month, leap year etc. Original values of the day and months must match the values in object Date.

Example of code for date validation by the help of Ajax follow.


<script type="text/javascript">
// ---------- validation on server by AJAX -------------
var req;
function serverValidate() {
  var inp = document.getElementById("dtInp").value
  var URL = ".../validateDate.asp?dt=" + escape(inp);
  if (window.XMLHttpRequest) {     // IE7, FF, Opera, ...
    req = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) { // <=IE6
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if(req) {
    req.onreadystatechange = processReq;
    req.open("GET", URL, true);
    req.send(null);
  } 
}

function processReq() {
  if(req.readyState == 4) {
    if(req.status == 200) {
      document.getElementById("testServer").innerHTML = req.responseText;
    }
  }
}
</script>

First function serverValidate() takes address of server script and adds queryString with date value, which is going to be tested by server script. Further according to browser type object AJAX is created. Function for response processing is attached and query is submitted. Entered value is encoded by function escape because of eventual non ASCII characters in data string.

The second function processReq() waits on server response. As soon as data message is received, function publishes validation result. Sample code is only illustration of principle validation by the help of AJAX, not code ready for entire form validation.


<%
' --- server skript (ASP classic) date validation by AJAX ---
Option Explicit
Response.Buffer = false

Dim dt

Call Response.AddHeader("Cache-Control", "no-cache")
If IsDate(request("dt")) Then
  dt = CDate(request("dt"))
  Response.Write FormatDateTime(dt, vbShortDate)
Else
  Response.Write "error"
End If
%>

To complete code examples, here is server script. Classic.asp and VBSript are used. Notice that just plain text is responded, no section like html, head, or body is used.

In the end alternate JavaScript code for date and time validation. Script is longer than first example, but enable more detailed determination of errors in date entry.


<script type="text/javascript">
// ------ another validation on client by JavaScript -------
var mList = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
function checkDateEU(value) {
  if(value == "") return false;
  var dt = value.split(".");
  if(dt.length != 3) return false;
  if(!dt[0] || !dt[1] || !dt[2]) return false;
  if(isNaN(dt[0]) || isNaN(dt[1]) || isNaN(dt[2])) return false;
  if(dt[2] > 2040 || dt[2] < 1990) return false;
  if(parseInt(dt[1]) > 12 || parseInt(dt[1]) < 1) return false;
  if(dt[2]/4 == parseInt(dt[2]/4))
  {  mList[1] = 29; }
  else
  {  mList[1] = 28; }
  if(dt[0] > mList[dt[1]-1] || dt[0] < 1) return false;
  return true;
}
function checkHour(value) {
  if(value == "") return false;
  var dt = value.split(":");
  if(dt.length != 2) return false;
  if(!dt[0] || !dt[1]) return false;
  if(isNaN(dt[0]) || isNaN(dt[1])) return false;
  if(parseInt(dt[0])>23 || parseInt(dt[0])<0) return false;
  if(parseInt(dt[1])>59 || parseInt(dt[1])<0) return false;
  return true;
}
</script>

updated 28.12.2007