Problème de script controle formulaire [Résolu/Fermé]

Signaler
-
Messages postés
689
Date d'inscription
vendredi 7 septembre 2007
Statut
Membre
Dernière intervention
25 mars 2015
-
Réservation /date / comparaisons / validation foumulaire

Bonjour, J'ai actuellement un problème avec le script qui est sensé contrôler et valider les informations contenues dans un formulaire.
Par exemple, partons du principe que le formulaire a pour but d'envoyer des réservations d'hôtels. Il doit contrôler que la date mentionnée
est valide de type dd/mm/yyyy et indique le jour même ou date ultérieure. Messages en cas d'erreur. Le reste je l'ai développé sans peine mais la j'avoue être un peu noub dans ce domaine de JS et je mélange un peu tout. Voici le code source de mon JS qui doit tester.
La variable du formulaire est checkin.

Merci de votre aide la je commence à m'énerver et c'est pour une virgule je pense.....


DOMHelper = {DGE:function(x){
		return document.getElementById(x)
  }
}
dh = DOMHelper;
dh.b = dh.DGE;

Date.prototype.isNorthAmerica = function(){
	return (this.getTimezoneOffset() < 660 && this.getTimezoneOffset() > 180);
}
Date.prototype.octopusDisplayFormat = function(){
  var mm = this.getMonth()+1;
  if(mm < 10) mm = "0" + mm;
  var dd = this.getDate();
  if(dd < 10) dd = "0" + dd;
  if(this.isNorthAmerica()){
	  return mm + "/" + dd + "/" + this.getFullYear();
  }
  else{
	  return dd + "/" + mm + "/" + this.getFullYear();
  }
}

today = new Date();
dFormat = today.isNorthAmerica()?"mm/dd/yyyy":"dd/mm/yyyy";

function makeEuroDate(str){
  var vals = str.split("/");
  var nDateString = vals[1] + "/" + vals[0] + "/" + vals[2];
  return new Date(nDateString);
}
function formatDateForURL(d){
	var month = d.getMonth() + 1;
	if(month < 10) month = "0" + month;
	var date = d.getDate();
	if(date < 10) date = "0" + date;
	return d.getFullYear() + "-" + month + "-" + date;
}
function getSelectedValue(id){
	try{
		var theSelect = DGE(id);
		return theSelect.options[theSelect.options.selectedIndex].value;
	}
	catch(Error){
	   return null;
	}
}
expDate = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/
function DGE(x){return document.getElementById(x)}
function validateDate(dateStr){
	if(!expDate.test(dateStr)) {return false;}
	var monthNumStr = today.isNorthAmerica() ? dateStr.split("/")[0]:dateStr.split("/")[1];
	var dateNumStr = today.isNorthAmerica()?dateStr.split("/")[1]:dateStr.split("/")[0];
	var yearNum = parseFloat(dateStr.split("/")[2]);
	var monthNum = parseFloat(monthNumStr);
	var dateNum = parseFloat(dateNumStr);
	var maxDate = 31;
	if(monthNum == 4 || monthNum == 5 || monthNum ==  6 || monthNum == 9 || monthNum == 11){
	  maxDate = 30;
	}
	else if (monthNum == 2){
	  if(yearNum %4 ==0) {maxDate = 29;}
	  else{
		 maxDate = 28;
	  }
	}
	var bValid= (dateNum <= maxDate && dateNum > 0 && monthNum <= 12 && monthNum > 0);
	return bValid;
}
function setCheckout(){
	var numNights = parseInt(DGE("nights").value);
	if(!isNaN(numNights)){
		var checkinDateVal = DGE("checkin").value;
		if(!expDate.test(checkinDateVal)){
		 //  alert("Fuck");
		}
		else if(!validateDate(checkinDateVal)){
		//   alert("Bitte geben Sie ein gültiges Anreisedatum ein");
		}
		else{
			var tDate = today.isNorthAmerica()?new Date(checkinDateVal):makeEuroDate(checkinDateVal);
			tDate.setDate(tDate.getDate() + numNights);
		  DGE("checkout").innerHTML = tDate.octopusDisplayFormat();
		}
	}
	else{
		alert("Bitte geben Sie eine gültige Anzahl Nächte ein");
	}
}
function unselectRadios(){
var theRadio = null;
var radios = document.getElementsByName("destinationRadio");
for(var i=0;i<radios.length;i++){
	if(radios[i].checked==true) {
	  theRadio = radios[i];
		}
		 }
if(theRadio != null) theRadio.checked=false;
}

function resetDestination(){
	var d = dh.b("destination");
	d.options.selectedIndex=0;
}
function makeURL(){
	//var tracker = document.getElementById("td_rdir").value;
	var destinationVal = getSelectedValue("destination");
	var dradios = document.getElementsByName("destinationRadio");
			var dradioVal = "";
            for(var i=0;i<dradios.length;i++){
               if(dradios[i].checked == true){
                 destinationVal= dradios[i].value;
                
               }
            }
	var checkinVal = DGE("checkin").value;
	var nightsVal = DGE("nights").value;
	var roomtypeVal = document.getElementById("roomtype").value;
	var roomsVal = document.getElementById("rooms").value;
	var starratingVal = document.getElementById("starrating").value;
		var bErrors = false;
		var errorMsg = "";
		var linebreak = "\n";
		var checkPace = new Date();
		var time = checkPace.getTime();
		var inputDate = document.getElementById("checkin").value;

	
		// COMPARE DATES
    function ParseDate( str1 )
    {
        // Parse the string in DD/MM/YYYY format
        re = /(\d{1,2})\/(\d{1,2})\/(\d{4})/
        var arr = re.exec( str1 );
        return new Date( parseInt(arr[3]), parseInt(arr[2], 10) - 1, parseInt(arr[1], 10) );
    }
		var userdate = ParseDate(document.getElementById("checkin").value);
		var userTime = userdate.getTime();

			
	 //checker si date entrée est périmée
	if(time >= userTime){
	errorMsg += "Bitte geben Sie ein gültiges Anreisedatum ein" ;
	bErrors = true;	
	}	
	if(destinationVal == 0){
	errorMsg = "Bitte wählen Sie eine Stadt aus "  + linebreak;
	bErrors = true;
	}
	if(!expDate.test(checkinVal) ){
		errorMsg += "Das eingegebene Anreisedatum muss in folgendem Format eingegeben werden: " + dFormat + linebreak;
		bErrors = true;	
	}
	if(isNaN(parseInt(nightsVal)))
	{
		errorMsg += "Bitte wählen Sie die Anzahl Nächte"  + linebreak;
		bErrors = true;
	}
	if(bErrors){
		alert(errorMsg);
		return;
	}
	var destinationArg = "&destination=" + destinationVal;
	var checkinArg = "";
		if(!expDate.test(checkinVal)){
			alert("Das eingegebene Anreisedatum muss in folgendem Format eingegeben werden: " + dFormat);
		}
		else if(!validateDate(checkinVal)){
		   alert("Bitte geben Sie ein gültiges Anreisedatum ein");
		}
		else{
			var tDate = today.isNorthAmerica()?new Date(checkinVal):makeEuroDate(checkinVal);
			checkinArg = "&checkin=" + formatDateForURL(tDate);
		}
	var nightsArg= nightsVal == ""?"":"&nights=" + nightsVal;
	var roomtypeArg = roomtypeVal == 0?"":"&roomtype=" + roomtypeVal;
	var roomsArg = roomsVal == 0?"":"&rooms=" + roomsVal;
	var starratingArg = starratingVal == 0?"":"&starrating=" + starratingVal;
	var URLRoot = "www.artik.ch";
	var URL = URLRoot + destinationArg + checkinArg + nightsArg + roomtypeArg + roomsArg + starratingArg;
//	var URL = URLRoot + destinationArg + checkinArg + nightsArg + roomtypeArg + roomsArg;
//	top.location.href = URL;
	window.open(URL, '', '');
	}
function init(){
   //var co = DGE("checkout");
   var ci = DGE("checkin");
   var ciDate = new Date(today);
   ciDate.setDate(ciDate.getDate() + 1)
   ci.value = ciDate.octopusDisplayFormat();
   ciDate.setDate(ciDate.getDate() + 1);
   //co.innerHTML = ciDate.octopusDisplayFormat();
}
function showHideCalendarhot(e, dateField, formName)
{
  var element = e.srcElement? e.srcElement : e.target;
  var leftPos = findPosX(element);
  var topPos = findPosY(element) + element.offsetHeight;

  if (document.getElementById("hotcalendar").style.visibility=="visible")
  {
    document.getElementById("hotcalendar").style.visibility="hidden";
  } 
  else if (document.getElementById("hotcalendar").style.visibility=="hidden")
  {
    var d = new Date();
    var currMonth = d.getMonth();
    var currYear = d.getFullYear();
    writeCalendarhot(currMonth, currYear, dateField, formName);
    document.getElementById("hotcalendar").style.visibility="visible";
    document.getElementById("hotcalendar").style.left = leftPos + 50;
    document.getElementById("hotcalendar").style.top = topPos - 105;
  }
}
function writeCalendarhot(month, year, dateField, formName)
{
  var monDate = new Date(year, month, 1);
  var firstDay = monDate.getDay();
  var monthDays = daysInMonth(month+1, year);

  var currDate = new Date();
  var currMonth = currDate.getMonth();
  var currDay = currDate.getDate();
  var currYear = currDate.getFullYear();

  var dayNames = new Array;
  dayNames.push("Sonday");
  dayNames.push("Monday");
  dayNames.push("Dieday");
  dayNames.push("Mitday");
  dayNames.push("Donday");
  dayNames.push("Friday");
  dayNames.push("Samday");
  var monthNames = new Array;
  monthNames.push("Januar");
  monthNames.push("Februar");
  monthNames.push("März");
  monthNames.push("April");
  monthNames.push("Mai");
  monthNames.push("Juny");
  monthNames.push("July");
  monthNames.push("August");
  monthNames.push("September");
  monthNames.push("Oktober");
  monthNames.push("November");
  monthNames.push("Dezember");
  var htmlCode = "";
  var day = 1;
  var nextMonth;
  var prevMonth;
  var nextYear = year;
  var prevYear = year;

  // Calculate next month and year
  if (month == 11) {
      nextMonth = 00;
      ++nextYear;
  } else { nextMonth = month+1; }

  // Calculate previous month and year
  if (month == 00) {
      prevMonth = 11;
      --prevYear;
  } else { prevMonth = month-1; }

  // Start the table
  htmlCode = "<table border='0' cellspacing='0'>";
  htmlCode += "<tr><th colspan='7'><a href='javascript:writeCalendarhot("+prevMonth+","+prevYear+", \""+dateField+"\", \""+formName+"\")' title='Show previous month'><<<\/a> "+monthNames[month]+" "+year+" <a href='javascript:writeCalendarhot("+nextMonth+","+nextYear+", \""+dateField+"\", \""+formName+"\")' title='Show next month'>>><\/a><\/th><\/tr><tr>";

  // Write the day names
  for (var i = 0; i < dayNames.length; i++)
  {
    htmlCode += "<th>"+dayNames[i].substring(0, 3)+"<\/th>";
  }
  htmlCode += "<\/tr><tr>";

  // Fill in empty values till the start of the month
  for (i = 0; i < firstDay; i++)
  {
    htmlCode += "<td> <\/td>";
  }

  // Fill in the rest of the week
  for (i = firstDay; i < 7; i++)
  {
	  if (year < currYear || (year == currYear && month < currMonth) || (year == currYear && month == currMonth && day < currDay))
      {
          htmlCode += "<td class='cross'>"+day+"<\/td>";
      }
      else
      {
          htmlCode += "<td><a href='javascript:setDateshot("+day+", "+month+", "+year+",\""+dateField+"\", \""+formName+"\")'>"+day+"<\/a><\/td>";
      }
      day++;
  }
  htmlCode += "<\/tr><tr>";

  // And then fill in the rest of the month
  while (day <= monthDays)
  {
    for (i = 0; i < 7; i++)
    {
      if (day <= monthDays)
      {
        if (year < currYear || (year == currYear && month < currMonth) || (year == currYear && month == currMonth && day < currDay))
        {
            htmlCode += "<td class='cross'>"+day+"<\/td>";  
        }
        else
        {
            htmlCode += "<td><a href='javascript:setDateshot("+day+", "+month+", "+year+", \""+dateField+"\", \""+formName+"\")' title='"+day+" "+monthNames[month]+" "+year+"'>"+day+"<\/a><\/td>";
        }
      }
      else
      {
        htmlCode += "<td> <\/td>";
      }
      day++;
    }
    htmlCode += "<\/tr><tr>";
  }
  
  htmlCode += "<\/tr><tr><td colspan='7' id='foot'><a href='javascript:;' onclick='showHideCalendarhot(event)' title='Fermer'>Schliessen<\/a><\/td><\/tr><\/table>";
  document.getElementById("hotcalendar").innerHTML = htmlCode;
}
function setDateshot(dateValue, monthValue, yearValue, dateField, formName)
{
    today = new Date();
	var chkIndate = today.isNorthAmerica()?padNumber(monthValue+1)+"/"+dateValue+"/"+yearValue:dateValue+"/"+padNumber(monthValue+1)+"/"+yearValue;
	eval("document."+formName+"."+dateField+".value = chkIndate");
//    setCheckout();
    document.getElementById("hotcalendar").style.visibility="hidden";
}
function padNumber(number)
{
  if (number < 10) {
    return "0"+number;
  } else { return number; }
}
function daysInMonth(month, year)
{
  if (year == null) {
    var d = new Date();
    year = d.getFullYear();
  }
  if (month == 4 || month == 6 || month == 9 || month == 11) {
    return 30;
  } else if (month == 2) {
    if (year % 4 == 0) {
      return 29;
    } else {
      return 28;
    }
  } else {
    return 31;
  }
}
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
<!-- GLB - eblws08 -->






LA page Html liée ( à placer dans le même dossier)

<script src="script.js"></script>
<style type="text/css">
<!--
.form11 {	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #254890;
	height: 15px;
	border: thin none #2B6882;
	border-color: #000000;
	border-width: 1px;
	border-left: 1px;
	width: 134px;
}	
.form12 {	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #254890;
	height: 15px;
	border: thin none #2B6882;
	border-color: #000000;
	border-width: 1px;
	border-left: 1px;
	width: auto;
}
.optHighlight{
	background-color:#b4c7e5; 
	font-weight:bold;
	}
.form2 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #254890;
	height: 16px;
	border: thin none #2B6882;
	border-color: #000000;
	border-width: 1px;
	border-left: 1px;
}
.form3 {
font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #254890;
	height: 16px;
	border: thin none #2B6882;
	border-color: #000000;
	border-width: 1px;
	border-left: 1px;
	width: 70px;
}
.formulaire {
	border: 1px solid #7F9DB9;
	height: 16px;
	font:Verdana, Arial, Helvetica, sans-serif;
	font-size:11px;
	background-color: #FFFFFF;
	color: #254890;
}
.jour {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #254890;
	height: 15px;
	border: thin none #2B6882;
	border-color: #000000;
	border-width: 1px;
	border-left: 1px;
	width: 70px;
}
.Titres {	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
	color: #FF9900;
	text-align: right;
}
.Titres1 {	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
	color: #FF9900;
	text-align: right;
}
.Titres2 {	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
	color: #0D359A;
	text-align: right;
}
.style3 {
	font-size: 12px;
	font-weight:bold;
	font-family: Arial, Helvetica, sans-serif;
	color: #20438d;
	border: 1px solid #79B8F2;
	width: 158px;
	height: 598px;
}
-->
</style>
<div id="hotcalendar" style="visibility:hidden;"></div>
<form id=rss_test name=rss_test onSubmit="return makeURL()" action="" method="post" target="_blank">
<input type="hidden" name="td_rdir" id="td_rdir" value="$$&url=">
<table class="style3" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td><div align="left">
      <table width="158" height="598" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td height="200"> </td>
        </tr>
        <tr>
          <td><table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="5" height="5"></td>
              <td> </td>
              <td width="5"></td>
            </tr>
            <tr>
              <td> </td>
              <td valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
                  <tr>
                    <td height="45" valign="top" class="Titres2">Städte<br />
                      <select style="width:145px;" name="destination" id="destination" onChange="unselectRadios()" tabindex="1" class="form12">
<option value="0">--Auswahl--</option>
<option value="CAUH">Abu Dhabi</option>
<option value="CACA">Acapulco</option>
                      </select></td>
                  </tr>
                  <tr>
                    <td height="40" valign="top" class="Titres2">Anreise<br />
                      <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr align="right">
                          <td width="79%"><input class="formulaire" type="text" name="checkin" id="checkin" size="13" tabindex="2"></td>
                          <td width="21%"><a href="javascript:;" onclick="showHideCalendarhot(event, 'checkin', 'rss_test')"></a></td>
                        </tr>
                      </table>
                      </td>
                  </tr>
                  <tr>
                    <td height="40" valign="top" class="Titres2">Nächte<br />
					<input class="formulaire" type="text" name="nights" value="1" id="nights" size="2" onBlur="setCheckout()" onFocus="this.select()" tabindex="3" style="width : 20px"></td>
                  </tr>
                  <tr>
                    <td height="45" valign="top" class="Titres2">Anzahl Zimmer<br />
					<select name="rooms" id="rooms" tabindex="5" class="form11" style="width : 35px">
                        <option value="1" selected>1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                      </select></td>
                  </tr>
				  <tr>
                    <td height="45" valign="top" class="Titres2">Kategorie<br />
					<select name="starrating" id="starrating" tabindex="5" class="form11" style="width : 60px">
       <option value="0">Alle</option>
      <option value="2-3">2-3 Sterne</option>
      <option value="3-4">3-4 Sterne</option>
      <option value="4-5">4-5 Sterne</option>
                      </select></td>
                  </tr>
                  <tr>
                    <td height="50" valign="top" class="Titres2">Zimmertyp<br />
                      <select name="roomtype" id="roomtype" tabIndex=4 class="form11" style="width:110px;">
      <option value="SB">Einzelzimmer</option>
      <option value="TB">Zweibett-Zimmer</option>
	  <option value="DB" selected>Doppelzimmer</option>
	  <option value="TS">Zweibett-Zi./1 Pers.</option>
      <option value="TR">Dreibett-Zimmer</option>
      <option value="Q">Vierbett-Zimmer</option>
                      </select></td>
                  </tr>
              </table></td>
              <td> </td>
            </tr>
          </table></td>
        </tr>
		<tr>
          <td height="100" valign="top"><input type="hidden" name="starrating" id="starrating" value="1-5" />
            </td>
        </tr>
      </table>
    </div></td>
  </tr>
</table>
</form>
<script language=javascript type="text/javascript">
<!--
init();
//-->
</script>

1 réponse

Messages postés
689
Date d'inscription
vendredi 7 septembre 2007
Statut
Membre
Dernière intervention
25 mars 2015
95
Je crois qu'on a tous la flemme de lire tout ton code, poste la fonction qui pose problème stp ;)
3
Merci

Quelques mots de remerciements seront grandement appréciés. Ajouter un commentaire

CCM 65492 internautes nous ont dit merci ce mois-ci