Da questa discussione è possibile estrarre il codice necessario per verificare che una data immessa in un campo testo sia una data valida e che sia espressa nel formato gg/mm/(aa)aa:
codice:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Esempio</title>
<script type="text/javascript">
// le seguenti righe di codice sono necessarie per rendere lo script compatibile con i vecchi browser; possono essere rimosse senza danno per i nuovi browser.
if (!Array.prototype.every) {
Array.prototype.every = function(fValidator /*, oThisObj */) {
"use strict";
if (this === void 0 || this === null) { throw new TypeError(); }
var aThisArray = Object(this);
var nLength = aThisArray.length >>> 0;
if (typeof fValidator !== "function") { throw new TypeError(); }
var oThisObj = arguments[1];
for (var iIndex = 0; iIndex < nLength; iIndex++) { if (iIndex in aThisArray && !fValidator.call(oThisObj, aThisArray[iIndex], iIndex, aThisArray)) { return false; } }
return true;
};
}
// fine delle righe di codice per la compatibilità
function validateForm() {
var iDateSegm, aInputDate = document.myForm.dateField.value.split("\/"), nInDateLen = aInputDate.length;
if (nInDateLen !== 3) { alert("Inserire una data nel formato gg\/mm\/(aa)aa"); return false; }
else {
for (var iSegmId = 0; iSegmId < nInDateLen; iSegmId++) {
iDateSegm = aInputDate[iSegmId];
if (/\D/.test(iDateSegm)) { alert("La data pu\u00F2 contenere solo numeri separati da \"\/\"."); return false; }
else { aInputDate[iSegmId] = parseFloat(iDateSegm); }
}
var oParsedDate = new Date(aInputDate[2], aInputDate[1] - 1, aInputDate[0]), aOutputDate = [oParsedDate.getDate(), oParsedDate.getMonth() + 1, oParsedDate.getFullYear()];
if (!aOutputDate.every(function (vThisValue, nThisIndex /*, aTheArray */) {
if (this[nThisIndex] === vThisValue) { return true };
return false;
}, aInputDate)) { return confirm("La data immessa \u00E8 stata corretta in " + aOutputDate.join("\/") + ". Confermare se la data corrisponde al valore che si voleva indicare, altrimenti annullare per apportare le dovute modifiche."); }
return false;
}
return true;
}
</script>
</head>
<body>
<form method="POST" name="myForm" onsubmit="return(validateForm());">
Inserire data: <input type="text" name="dateField" id="dateField" /> <input type="submit" value="Invia">
</form>
</body>
</html>