Validation et formatage d'une date

Description

Un objet javascript pour valider et formater une date à partir d'un objet Date ou une chaine de caractères.
En cas d'erreur, les codes d'erreur permettent d'afficher un message précis. Par exemple: Le mois en incorrect.
La chaine de caractères qui contient la date peut être encodée avec ou sans séparateurs;
Le fichier Zip contient une page html et un fichier javascript.

La page html permet de tester la validation et le formatage. L'aide se retrouve aussi sur cette page.
Le code est directement testable à l'adresse http://2502.no-ip.com/dateValidator/

Source / Exemple :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		<title>Page de test pour DateValidator</title>
		<link href='http://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css' />
		<script type="text/javascript">
			function DateValidator(aValue, aIsDateWithTime)
			{
				if(aValue.length || 0)
				{
					this.lastCodeError = this.valid(aValue, aIsDateWithTime);
					this.isValid = (this.lastCodeError == 0);
					if (this.isValid == true) {
						this.value = aValue;
						this.isDateWithTime = aIsDateWithTime;
						this.date = new Date(Date.UTC(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliSeconds));
					}
				}
				else
				{
					this.date = new Date(aValue.getTime() - (aValue.getTimezoneOffset() * 60000))
					this.value = this.format('%dd/%mm/%yyyy %hh:%dd:%ss');
					this.isDateWithTime = aIsDateWithTime;
				}
			}

			// valid date
			DateValidator.prototype.valid = function(aValue, aIsDateWithTime) {
				if(aValue.length < 6)
				{
					return -10;
				}
				
				aValue = aValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
				
				var regex;
				if ((isNaN(aIsDateWithTime) == false) && (typeof(aIsDateWithTime) != 'undefined') && (aIsDateWithTime == true) || aValue.length >= 12) {
					regex = new RegExp("^(\\d{1,2})[\\- :/]?(\\d{1,2})[\\- :/]?(\\d{2,4})([\\- :/]?(\\d{1,2})[\\- :/]?(\\d{1,2})[\\- :/]?(\\d{1,2})[\\- :./]?(\\d{0,3}))?$");
				}
				else {
					regex = new RegExp("^(\\d{1,2})[\\- :/]?(\\d{1,2})[\\- :/]?(\\d{2,4})$");
				}

				var result = regex.exec(aValue);
				if (result == null) {
					return -1; // Incorrect format
				}

				this.day = parseInt(result[1], 10);
				this.month = parseInt(result[2], 10) - 1;
				this.year = parseInt(result[3], 10);
				this.hours = parseInt(result[5], 10);
				this.minutes = parseInt(result[6], 10);
				this.seconds = parseInt(result[7], 10);
				this.milliSeconds = parseInt(result[8], 10);

				if (this.year < 100) {
					var toDay = new Date();
					ss = Math.floor(toDay.getFullYear() / 100);
					yy = toDay.getFullYear() - (ss * 100);
					if (this.year > (yy + 20)) {
						ss = ss - 1;
					}

					this.year += (ss * 100);
				}

				if ((this.year < 1583) || (this.year > 9999)) {
					return -2; // Year out of bound
				}

				if ((this.month < 0) || (this.month > 11)) {
					return -3; // Month out of bound;
				}

				var dayMaxInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
				if (((this.year % 4) == 0 && (this.year % 100) != 0) || (this.year % 400) == 0) {
					dayMaxInMonth[1] = 29;
				}

				if ((this.day < 1) || (this.day > dayMaxInMonth[this.month])) {
					return -4; // Day out of bound;
				}

				if (isNaN(this.hours) == true) {
					this.hours = 0;
				}
				else {
					if (this.hours < 0 || this.hours > 59) {
						return -5; // hours out of bound;
					}
				}

				if (isNaN(this.minutes) == true) {
					this.minutes = 0;
				}
				else {
					if (this.minutes < 0 || this.minutes > 59) {
						return -6; // minutes out of bound;
					}
				}

				if (isNaN(this.seconds) == true) {
					this.seconds = 0;
				}
				else {
					if (this.seconds < 0 || this.seconds > 59) {
						return -7; // seconds out of bound;
					}
				}

				if (isNaN(this.milliSeconds) == true) {
					this.milliSeconds = 0;
				}

				return 0; // youpie, no error
			}

			DateValidator.prototype.formatVerbose = function(aFormat, aDays, aMonths, aNumberDay) {
				if (this.date != null) {
					var utc = /([^%]?)(%utc)/g;
					var ddd = /([^%]?)(%ddd)/g;
					var Ddd = /([^%]?)(%Ddd)/g;
					var DDD = /([^%]?)(%DDD)/g;
					var dd = /([^%]?)(%dd)/g;
					var D = /([^%]?)(%D)/g;
					var d = /([^%]?)(%d)/g;
					var mmm = /([^%]?)(%mmm)/g;
					var Mmm = /([^%]?)(%Mmm)/g;
					var MMM = /([^%]?)(%MMM)/g;
					var mm = /([^%]?)(%mm)/g;
					var m = /([^%]?)(%m)/g;
					var yyyy = /([^%]?)(%yyyy)/g;
					var yy = /([^%]?)(%yy)/g;
					var hh = /([^%]?)(%hh)/g;
					var h = /([^%]?)(%h)/g;
					var MM = /([^%]?)(%MM)/g;
					var M = /([^%]?)(%M)/g;
					var ss = /([^%]?)(%ss)/g;
					var s = /([^%]?)(%s)/g;

					var tmpDate;
					if (aFormat.match(utc)) {
						tmpDate = this.date
						aFormat = aFormat.replace(utc, '');
					}
					else {
						tmpDate = new Date(this.date.getTime() + (this.date.getTimezoneOffset() * 60000));
					}

					if (aFormat.match(ddd)) {
						var dayInWeek = tmpDate.getDay();
						if (dayInWeek < 0) {
							dayInWeek = 6;
						}
						aFormat = aFormat.replace(ddd, '$1' + aDays[dayInWeek].toLowerCase());
					}

					if (aFormat.match(Ddd)) {
						var dayInWeek = tmpDate.getDay();
						if (dayInWeek < 0) {
							dayInWeek = 6;
						}
						aFormat = aFormat.replace(Ddd, '$1' + aDays[dayInWeek].charAt(0).toUpperCase() + aDays[dayInWeek].substr(1));
					}

					if (aFormat.match(DDD)) {
						var dayInWeek = tmpDate.getDay();
						if (dayInWeek < 0) {
							dayInWeek = 6;
						}
						aFormat = aFormat.replace(DDD, '$1' + aDays[dayInWeek].toUpperCase());
					}

					if (aFormat.match(dd)) {
						var dayOfMonth = tmpDate.getDate();
						aFormat = aFormat.replace(dd, '$1' + (dayOfMonth < 10 ? '0' + dayOfMonth : dayOfMonth));
					}

					if (aFormat.match(D)) {
						var dayOfMonth = tmpDate.getDate();
						if (aNumberDay != null && dayOfMonth <= aNumberDay.length) {
							aFormat = aFormat.replace(D, '$1' + aNumberDay[dayOfMonth - 1]);
						}
						else {
							aFormat = aFormat.replace(D, '$1' + dayOfMonth);
						}
					}

					if (aFormat.match(d)) {
						var dayOfMonth = tmpDate.getDate();
						aFormat = aFormat.replace(d, '$1' + dayOfMonth);
					}

					if (aFormat.match(mmm)) {
						var month = tmpDate.getMonth();
						aFormat = aFormat.replace(mmm, '$1' + aMonths[month].toLowerCase());
					}

					if (aFormat.match(Mmm)) {
						var month = tmpDate.getMonth();
						aFormat = aFormat.replace(Mmm, '$1' + aMonths[month].charAt(0).toUpperCase() + aMonths[month].substr(1));
					}

					if (aFormat.match(MMM)) {
						var month = tmpDate.getMonth();
						aFormat = aFormat.replace(MMM, '$1' + aMonths[month].toUpperCase());
					}

					if (aFormat.match(mm)) {
						var month = tmpDate.getMonth() + 1;
						aFormat = aFormat.replace(mm, '$1' + (month < 10 ? '0' + month : month));
					}

					if (aFormat.match(m)) {
						var month = tmpDate.getMonth() + 1;
						aFormat = aFormat.replace(m, '$1' + month);
					}

					if (aFormat.match(yyyy)) {
						var year = tmpDate.getFullYear();
						aFormat = aFormat.replace(yyyy, '$1' + year);
					}

					if (aFormat.match(yy)) {
						var year = tmpDate.getFullYear() % 100;
						aFormat = aFormat.replace(yy, '$1' + year);
					}

					if (aFormat.match(hh)) {
						var hours = tmpDate.getHours();
						aFormat = aFormat.replace(hh, '$1' + (hours < 10 ? '0' + hours : hours));
					}

					if (aFormat.match(h)) {
						var hours = tmpDate.getHours();
						aFormat = aFormat.replace(h, '$1' + hours);
					}

					if (aFormat.match(MM)) {
						var minutes = tmpDate.getMinutes();
						aFormat = aFormat.replace(MM, '$1' + (minutes < 10 ? '0' + minutes : minutes));
					}

					if (aFormat.match(M)) {
						var minutes = tmpDate.getMinutes();
						aFormat = aFormat.replace(M, '$1' + minutes);
					}

					if (aFormat.match(ss)) {
						var seconds = tmpDate.getSeconds();
						aFormat = aFormat.replace(ss, '$1' + (seconds < 10 ? '0' + seconds : seconds));
					}

					if (aFormat.match(s)) {
						var seconds = tmpDate.getSeconds();
						aFormat = aFormat.replace(s, '$1' + seconds);
					}
				}
				return aFormat;
			}

			DateValidator.prototype.format = function(aFormat) {
				return this.formatVerbose(aFormat, null, null, null);
			}

			DateValidator.prototype.formatDDMMSSYY = function() {
				return this.formatVerbose('%dd/%mm/%yyyy');
			}

			DateValidator.prototype.formatSSYYMMDDToDate = function() {
				var result = new Date(this.year, this.month - 1, this.day, 0, 0, 0, 0);
				return result;
			}

			DateValidator.prototype.formatSSYYMMDDToDateUTC = function() {
				var result = new Date(Date.UTC(this.year, this.month - 1, this.day, 0, 0, 0, 0));
				return result;
			}
		</script>
		<style type="text/css">
			<!--
			Body
			{
				font-size: 10pt; 
				color: #606060; 
				font-family: 'Arimo', sans-serif;
				background-color: #fafafa;
			}
			
			TD
			{
				padding-top : 2px;
				padding-bottom : 2px;
			}
			
			TR.Header
			{
				background: #c0c0c0;
				color: #ffffff;
			}

			TR.Pair
			{
				background: #f0f0f0;
			}
			
			TR.Inpair
			{
				background: #e0e0e0;
			}
			-->
		</style>
	</head>
	<body>
		<script type="text/javascript" language="javascript">
			// libelle pour le formatage
	        var textDay = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
			var textNumber = new Array('premier');
			var textMois = new Array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre');

			function showDate(textBoxId, cbFormatId, labelId)
			{
				var textBox = document.getElementById(textBoxId);
				var label = document.getElementById(labelId);
				var cbFormat = document.getElementById(cbFormatId);
				var result = '';
				
				var dateValidator = new DateValidator(textBox.value);
				switch(dateValidator.lastCodeError)
				{
					case 0: // pas d'erreur
					{
						result = '<b>' + dateValidator.formatVerbose(cbFormat.value, textDay, textMois, textNumber) + '</b>';
						break;
					}
					case -10: // pas assez de caractère
					{
						result = 'Erreur: Pas assez de caractères';
						break;
					}
					case -1: // format incorrect
					{
						result = 'Erreur: Format incorrect';
						break;
					}
					case -2: // année
					{
						result = 'Erreur: Année incorrect';
						break;
					}
					case -3: // mois
					{
						result = 'Erreur: Mois incorrect';
						break;
					}
					case -4: // jour
					{
						result = 'Erreur: Jour incorrect';
						break;
					}
					case -5: // heure
					{
						result = 'Erreur: Heure incorrect';
						break;
					}
					case -6: // minute
					{
						result = 'Erreur: Minute incorrect';
						break;
					}
					case -7: // minute
					{
						result = 'Erreur: Seconde incorrect';
						break;
					}
					default:
						result = 'Erreur inconnue';
						break;
				}
				
				label.innerHTML = result;
			}
		
		</script>

		<table style="border-bottom:1px dotted blue">
			<tr>
				<td colspan='3' style="border-bottom:1px dotted blue">
					<b>DateValidator</b> permet de valider et de formater une date comprise entre le 01/01/1583 et 31/12/9999 (le calendrier grégorien commença le 15 octobre 1582).<br/>
					Le format de saisie est relativemant souple (jour mois année heure minute seconde).Seul l'ordre de saisie à de l'importance jour suivi de mois, suivi de l'année etc...</br/>
					L'usage de séparateur n'est pas obligatoire saul dans les cas ambigüs (pex: 21260 doit être 21/2/60 ou 2/12/60)<br/>
					Le code fonctionne sur tous les browsers modernes (Internet explorer 6, 7, 8..., Opera, Safari, Chrome, Firefox)
				</td>
			</tr>
			<tr>
				<td style='text-align:right'>Entrez une date:</td>
				<td><input id='tbDate' type="text" value="25/2/1960 3:58:5" maxlength="19" size="19" onkeyup="javascript:showDate(this.id, 'cbFormat', 'lblDate')"/></td>
				<td>
					<select id='cbFormat' onchange="javascript:showDate('tbDate', this.id, 'lblDate')">
						<option value='%d/%m/%yy'>%d/%m/%yy</option>
						<option value='%dd/%mm/%yyyy'>%dd/%mm/%yyyy</option>
						<option value='%dd %mmm %yy'>%dd %mm %yy</option>
						<option value='%Ddd le %D %mmm %yyyy'>%Ddd le %D %mmm %yyyy</option>
						<option value='%yyyy%mm%dd %hh%MM%ss'>%yyyy%mm%dd %hh%MM%ss</option>
						<option value='%dd%mm%yyyy %hh%MM%ss'>%dd%mm%yyyy %hh%MM%ss</option>
						<option value='%dd-%mm-%yyyy %hh:%MM:%ss'>%dd-%mm-%yyyy %hh:%MM:%ss</option>
						<option value='%Ddd le %D %mmm %yyyy %hh heure(s) %MM minute(s) %ss seconde(s)'>Ddd le %D %mmm %yyyy %hh heure(s) %MM minute(s) %ss seconde(s)</option>
						<option selected='selected' value='</b>Jour: <b>%ddd</b>, numéro: <b>%d</b>, Mois: <b>%mmm</b>, Année: <b>%yyyy</b>, Heure: <b>%h</b>,  Minute: <b>%M</b>, Seconde: <b>%s</b>'></b></b>Jour: <b>%ddd</b>, numéro: <b>%d</b>, Mois: <b>%mmm</b>, Année: <b>%yyyy</b>, Heure: <b>%h</b>,  Minute: <b>%M</b>, Seconde: <b>%s</b></b></option>
					</select>
				</td>
			</tr>
			<tr>
				<td style='text-align:right'>Resultat:</td>
				<td colspan='2'><span id='lblDate'/></td>
			</tr>
		</table>

		<table style="border:0px; padding:0px; margin:0px; border-spacing:0px; border-collapse:collapse;">
			<tr>
				<td colspan='2'><b>Jour</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td style='width:80px'>%d</td>
				<td>jour sans 0</td>
			</tr>
			<tr>
				<td>%D</td>
				<td>jour avec du texte spécifique</td>
			</tr>
			<tr>
				<td>%dd</td>
				<td>jour avec 0</td>
			</tr>
			<tr>
				<td>%ddd</td>
				<td>jour en lettres minuscules</td>
			</tr>
			<tr>
				<td>%DDD</td>
				<td>jour en lettres majuscules</td>
			</tr>
			<tr>
				<td>%Ddd</td>
				<td>jour en lettres minuscules sauf la première</td>
			</tr>
			<tr>
				<td colspan='2'><b>Mois</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td>%m</td>
				<td>mois sans 0</td>
			</tr>
			<tr>
				<td>%mm</td>
				<td>mois avec 0</td>
			</tr>
			<tr>
				<td>%mmm</td>
				<td>mois en lettres minuscules</td>
			</tr>
			<tr>
				<td>%MMM</td>
				<td>mois en lettres majuscules</td>
			</tr>
			<tr>
				<td>%Mmm</td>
				<td>mois en lettres minuscules sauf la première</td>
			</tr>
			<tr>
				<td colspan='2'><b>Année</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td>%yy</td>
				<td>année en 2 chiffres</td>
			</tr>
			<tr>
				<td>%yyyy</td>
				<td>année en 4 chiffres</td>
			</tr>
			<tr>
				<td colspan='2'><b>Heure</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td>%h</td>
				<td>heure sans 0</td>
			</tr>
			<tr>
				<td>%hh</td>
				<td>heure avec 0</td>
			</tr>
			<tr>
				<td colspan='2'><b>Minute</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td>%M</td>
				<td>minute sans 0</td>
			</tr>
			<tr>
				<td>%MM</td>
				<td>minute avec 0</td>
			</tr>
			<tr>
				<td colspan='2'><b>Seconde</b></td>
			</tr>
			<tr>
				<td colspan='2' style='height:2px; background-color: #B0B0B0' />
			</tr>
			<tr>
				<td>%s</td>
				<td>seconde sans 0</td>
			</tr>
			<tr>
				<td>%ss</td>
				<td>seconde avec 0</td>
			</tr>
		</table>
		
		<script type="text/javascript" language="javascript">
			var date = new Date();
			
			var dateValidator = new DateValidator(date);
			var formatArray = new Array('%dd/%mm/%yyyy', '%yyyy:%mm:%dd', '%dd/%mm/%yyyy %hh:%mm:%ss', '%d/%m/%yy', '%ddd %dd %mmm %yyyy', '%Ddd %dd %Mmm %yyyy', '%DDD %dd %MMM %yyyy', '%Ddd le %dd %mmm %yyyy, %h heure(s) %m minute(s) %s seconde(s)');

			document.write('<br/>Date pour le test: <b>' + date + '</b><br/>');
			
			document.write('<table>');
			document.write('<tr class="Header"><td>Format (dateValidator.formatVerbose(xyz))</td><td>Resultat</td></tr>');
			var trClass;
			var pair = false;
			for(var i=0; i < formatArray.length; i++)
			{
				trClass = (pair = !pair) == true ? "Pair" : "Inpair"
				document.write('<tr class="' + trClass + '"><td>' + formatArray[i] + '</td><td>' + dateValidator.formatVerbose(formatArray[i], textDay, textMois, textNumber) + '</td></tr>');
			}
			
			dateValidator = new DateValidator("01/02/2025");
			document.write('<tr><td></td><td></td></tr>');
			
			trClass = (pair = !pair) == true ? "Pair" : "Inpair"
			document.write('<tr class="' + trClass + '"><td>%Ddd le %D %mmm %yyyy</td><td>' + dateValidator.formatVerbose('%Ddd le %D %mmm %yyyy', textDay, textMois, textNumber) + '</td></tr>');

			dateValidator = new DateValidator("02/02/2025");
			trClass = (pair = !pair) == true ? "Pair" : "Inpair"
			document.write('<tr class="' + trClass + '"><td>%Ddd le %D %mmm %yyyy</td><td>' + dateValidator.formatVerbose('%Ddd le %D %mmm %yyyy', textDay, textMois, textNumber) + '</td></tr>');

			document.write('</table>');
			
			showDate('tbDate', 'cbFormat', 'lblDate');
			
			document.getElementById('tbDate').focus();
		</script> 
	</body>
</html>

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.