Foros del Web » Programando para Internet » Javascript »

Validación fecha.

Estas en el tema de Validación fecha. en el foro de Javascript en Foros del Web. Buenas aqui les mando el formulario q me ha hecho romper la cabeza: Nota: Tengo q verificar bien el asunto antes de q se ingrese. ...
  #1 (permalink)  
Antiguo 12/05/2004, 16:50
 
Fecha de Ingreso: mayo-2004
Ubicación: Chilito lindo
Mensajes: 26
Antigüedad: 20 años
Puntos: 0
Validación fecha.

Buenas aqui les mando el formulario q me ha hecho romper la cabeza:

Nota: Tengo q verificar bien el asunto antes de q se ingrese. hasta ahora verifica e ingresa, pero cuando le mando un dato erroneo. tiene q actualizar la fecha q estaba. es decir si esta mal, q siga mostrando la fecha q estaba. Hasta ahora solo queda en 00/00/0000...

Las Validaciones las llamo por requiere...

VALIDA:

var pFecha = "ERROR: Fecha no válida, el formato es: dd/mm/aaaa";

function isFecha (s)
{
if (s)
{
borrar =s;
if ((s.substr(2,1) == "/") && (s.substr(5,1) == "/"))
{
for (i=0; i<10; i++)
{
if (((s.substr(i,1)<"0") || (s.substr(i,1)>"9")) && (i != 2) && (i != 5))
{
borrar = '';
break;
}
}
if (borrar)
{
a = s.substr(6,4);
m = s.substr(3,2);
d = s.substr(0,2);
if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
borrar = '';
else
{
if((a%4 != 0) && (m == 2) && (d > 28))
borrar = ''; // Año no viciesto y es febrero y el dia es mayor a 28
else
{
if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
borrar = '';
} // else
} // fin else
} // if (error)
} // if ((s.substr(2,1) == "/") && (s.substr(5,1) == "/"))
else
borrar = '';
if (borrar == '')
return false;
else
return true;
} // if (s)
}

.
.
.

function checkField (theField, theFunction, emptyOK, s)
{
var msg;
if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
if (checkField.arguments.length == 4) {
msg = s;
} else {
if( theFunction == isAlphabetic ) msg = pAlphabetic;
if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
if( theFunction == isInteger ) msg = pInteger;
if( theFunction == isNumber ) msg = pNumber;
if( theFunction == isEmail ) msg = pEmail;
if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
if( theFunction == isName ) msg = pName;
if( theFunction == isFecha ) msg = pFecha;
}

if ((emptyOK == true) && (isEmpty(theField.value))) return true;

if ((emptyOK == false) && (isEmpty(theField.value)))
return warnEmpty(theField);

if (theFunction(theField.value) == true)
return true;
else
return warnInvalid(theField,msg);

}


formulario:

<script language="JavaScript" type="text/javascript">
function verificar () {
if( checkField( document. carta_aceptacion. fecha_c_aceptacion, isFecha, false ) )
alert( "Todo verificado con exito" );
};
</script>
.
.
.
<form action="<?php echo $editFormAction;?>" method="POST" name="carta_aceptacion" id="carta_aceptacion" onSubmit="return verificar()">
<p>&nbsp;</p>
<TABLE width="333" height="72" align=center>
<tr>
<TD height="34" colspan="5"><div align="center"><span class="titulo"><font face="Arial">Carta de Aceptaci&oacute;n</font></span> </div>
<td width="14"><div align="center"></div></td>
</tr>
<tr>
<TD width="25" height="30"><div align="center"></div></td>
<TD width="37" valign="top"><div align="center"><font face="Arial"><span class="texto_formulario">Fecha</span></font></div></td>
<TD width="52" valign="top"><div align="center">
<input name="fecha_c_aceptacion" type="text" class="resultado_celda" id="fecha_c_aceptacion" value="<?php echo $fecha_acta_bd; ?>" size="15">

</div></td>
<TD width="51" valign="top"><div align="center"><span class="formato_fecha"><font face="Arial">dd/mm/aaaa</font></span></div></td>
<TD width="115" colspan="2" valign="top"><div align="center"><font face="Arial"></font></div></td>
</tr>

</TABLE>

<table width="261" border="0" align="center">
<tr>
<td width="80"><font face="Arial">
<input name="atras" type="button" class="boton" onClick="javascript:actualiza_1_frames('<?php echo $cod_beca ?>', document.forms['parametros_atras'])" value="Atrás">
</font></td>
<td width="80"><font face="Arial">
<input name="grabar" type="submit" class="boton" id="grabar" value="Grabar">
</font></td>
<td width="94"><font face="Arial">
<input name="SUBMIT2" type="button" class="boton" onClick="javascript:actualiza_2_frames('<?php echo $cod_beca ?>', document.forms['parametros'])" value="Siguiente">
</font></td>
</tr>
</table>

si alguien entendio?? porfa q me ayude...
¿O les falte algun dato mas?

__________________
Aguante San Luis- Este año en primera...

Última edición por Cluster; 13/05/2004 a las 05:56
  #2 (permalink)  
Antiguo 13/05/2004, 05:01
Avatar de vitxo  
Fecha de Ingreso: septiembre-2003
Ubicación: Valencia
Mensajes: 219
Antigüedad: 20 años, 7 meses
Puntos: 0
No tengo tiempo para tragarme todo el código, mal formateado = poco legible, que has pegado, pero igual te interesaría estudiar el patrón FormController. Aligera mucho código repetitivo y simplifica la validación de campos del formulario.
En el wiki de http://wact.sf.net/ tienes información, además si buscas por FormController en este foro darás con un hilo de hace unos meses.

Por cierto, un año es bisiesto y tu problema no es de PHP, sino de javascript? No entiendo.

Última edición por vitxo; 13/05/2004 a las 05:03
  #3 (permalink)  
Antiguo 13/05/2004, 05:55
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 4 meses
Puntos: 129
Lo que necesitas es alguien que sepa algo de Javascript .. no de PHP (y menos un "experto").


Pero .. deberías hacer dicha validación también en PHP antes de ingresar ese dato en tu BD o donde lo proceses.

Un saludo,

PD: cambio el título y muevo el mensaje al foro de Javascript.
__________________
Por motivos personales ya no puedo estar con Uds. Fue grato haber compartido todos estos años. Igualmente los seguiré leyendo.
  #4 (permalink)  
Antiguo 13/05/2004, 08:50
 
Fecha de Ingreso: mayo-2004
Ubicación: Chilito lindo
Mensajes: 26
Antigüedad: 20 años
Puntos: 0
De Vuelta con la Tonterits

El punto sig. para terminar con esta tontera luego, es la siguiente:

Estoy Metido en un forro de crear un sistema en Intranet. Y lo que me esta faltando es Validar los malditos campos q el usuario va Ingresar..

Hasta ahora si ingreso un dato BIEN lo verifica y lo Ingresa....

Si esta MAL lo verifica pero me deja el campo en 00/00/000..

Y lo que quieren estos malditos Explotadores, es q en cierta forma se actualize la fecha.. Es decir si el dato esta mal me deje la fecha q estaba ANTES puesta.

Entonces. Cual puede ser el problema????

¿Onsubmit?
¿OnClick?
¿Submit?
¿Button?

¿¿¿Q es lo Mejor???


-->
__________________
Aguante San Luis- Este año en primera...
  #5 (permalink)  
Antiguo 17/05/2004, 15:19
Avatar de Xphoenix  
Fecha de Ingreso: abril-2004
Mensajes: 96
Antigüedad: 20 años
Puntos: 0
Prueba esto a ver si te sirve

<HTML>
<HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">

<TITLE>Validar tu Edad</TITLE>

</HEAD>
<BODY onLoad="document.forms[0].day.focus();">
<div align="center">
<script language="javascript">
function EsAdulto(fecha_nacimiento)
{
if(!IsDate(fecha_nacimiento))
return false; var fecha=new Date(fecha_nacimiento);
var nyear=fecha.getFullYear();
var nmonth=fecha.getMonth();
var hyear=(new Date()).getFullYear();
var hmonth=(new Date()).getMonth();
var ndays=nyear*365 + (nmonth)*30;
var hdays=hyear*365 + (hmonth)*30;
return (hdays-ndays) > (18*365);
}
function IsDate(inString)
{
inString += " "; //add some padding so call is not made out of bounds
outString = "";
endString = "";
if (Trim(inString).length == 2)
return false;
if (inString.indexOf("/") == 0)
outString = "00/";
if (inString.indexOf("/") == 1)
outString = "0" + inString.charAt(0) + "/";
if (inString.indexOf("/") == 2)
outString = inString.substr(0,3);
endString = inString.substring(inString.indexOf("/") + 1,inString.length);
if (endString.indexOf("/") == 0)
outString += "00/";
if (endString.indexOf("/") == 1)
outString += "0" + endString.charAt(0) + "/";
if (endString.indexOf("/") == 2)
outString += endString.substr(0,3);
endString = endString.substring(endString.indexOf("/") + 1,endString.length);
endString = Trim(endString);
outString += endString;
if (isDate(outString.substr(3,2),outString.substr(0,2 ),outString.substr(6,4)))
return true;
return false;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isDate (month,day,year)
{
var today = new Date();
year = ((!year) ? y2k(today.getYear()):year);
month = ((!month) ? today.getMonth():month-1);
if (!day) return false
var test = new Date(year,month,day);
if ( (y2k(test.getYear()) == year) &&
(month == test.getMonth()) &&
(day == test.getDate()) )
return true;
else
return false
}

function Trim(inString)
{
while (inString.length > 0)
{
if (inString.substring(0, 1) != " ")
break;
inString = inString.substring(1, inString.length);
}

while (inString.length > 0)
{
if (inString.substring(inString.length - 1, inString.length) != " ")
break;
inString = inString.substring(0, inString.length - 1);
}

return inString;
}

function valida()
{ fecha = document.forms[0].day.value + "/" + document.forms[0].month.value+ "/" +document.forms[0].year.value;
if(!EsAdulto(fecha))
{
alert("Lo sentimos. Usted no cumple los requisitos");
document.forms[0].day.focus();
return false;
}
return true;
}

function Pass(I){
if (document.forms[0].day.value > 31) {
alert("Los días deben estar entre (1-31)");
document.forms[0].day.focus();
return false;
}
if (I == 2){
document.forms[0].month.focus();
document.forms[0].month.value='';
return true;
}

}
function Pass2(I){
if (document.forms[0].month.value > 12) {
alert("Los meses deben estar entre (1-12)");
document.forms[0].month.focus();
document.forms[0].month.value='';
return false;
}
if(I == 2) {
document.forms[0].year.focus();
document.forms[0].year.value='';
return true;
}

}
</script>
<p>&nbsp;</p>
<table width="500" height="380" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div align="center">
<table width="502" border="0" cellspacing="0" cellpadding="0">
<tr>

</tr>
</table>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong><br>
Para poder accesar a este sitio debe ser mayor de 18 a&ntilde;os.<br>
Por favor ingrese su fecha de nacimiento. </strong></font> </p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>D&iacute;a
/ Mes / A&ntilde;o</strong></font></p>
</div>
<form action="web_introduccion.html" onsubmit="return valida()">
<div align="center">
<p>
<input type="text" name="day" maxlength="2" value="" size="2" onKeyPress="Pass(this.value.length); if ((event.keyCode > 47) && (event.keyCode < 58)) event.returnValue = true; else return false;" onFocus="this.value=''">
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>/</strong></font>
<input type="text" name="month" maxlength="2" value="" size="2" onKeyPress="Pass2(this.value.length); if ((event.keyCode > 47) && (event.keyCode < 58)) event.returnValue = true; else return false;">
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong> / </strong></font>
<input type="text" name="year" maxlength="4" value="" size="4" onKeyPress="if ((event.keyCode > 47) && (event.keyCode < 58)) event.returnValue = true; else return false;">
</p>
<p>
<input type="submit" value="Ingresar">
</p>
</div>
</form></td>
</tr>
</table>

</div>

</BODY>
</HTML>
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:48.