Foros del Web » Programando para Internet » Javascript »

validar antes de guardar

Estas en el tema de validar antes de guardar en el foro de Javascript en Foros del Web. hola a todos tengo un pequeño problema. tengo un formulario que en la base tiene 4 llaves primaria que son FOLIO CVE_MED ID FOLIO_CER Y ...
  #1 (permalink)  
Antiguo 09/02/2012, 11:51
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
validar antes de guardar

hola a todos tengo un pequeño problema.

tengo un formulario que en la base tiene 4 llaves primaria que son

FOLIO
CVE_MED
ID
FOLIO_CER

Y quisiera que mi formulario antes de mandarlo a guardar checara que esos campos no estén vacíos, que siempre deban de estar llenos, como puedo hacer eso?????

la verdad soy novato y espero que me puedan ayudar de antemano les doy las gracias y perdon por las molestias

Saludos buena tarde
  #2 (permalink)  
Antiguo 09/02/2012, 12:06
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: validar antes de guardar

buenas,
no en javascript. eso lo debes de manejar en el lenguaje de servidor que estés utilizando. intentar buscar una solución por el lado cliente es simplemente una mal decisión.

si lo requieres, reporta el tema y solicita que muevan el tema al foro del lenguaje que estes utilizando.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #3 (permalink)  
Antiguo 09/02/2012, 12:19
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

eso lo puedes hacer facil con js, digamos que el input para los campos es el siguiente:

Código HTML:
Ver original
  1. <form id="forma">
  2. Folio<input type="text" name="campo1"/>
  3. CVE_MED<input type="text" name="campo2"/>
  4. ID<input type="type" name="campo3"/>
  5. FOLIO_CER</input type="text" name="campo4"/>
  6. <input type="button" onclick="validar()"/>
  7. </form>

y este seria tu codigo javascript:
Código Javascript:
Ver original
  1. function validar(){
  2.    for(var i=0;i<=4;i++){
  3.       if(document.getElementsByName("campo"+i)[0].value==""){
  4.          alert("Por favor llene todos los campos.");
  5.          return false;
  6.       }
  7.       else{
  8.          document.getElementById("forma").submit();
  9.       }
  10.    }
  11. }

espero esto te sirva de ayuda =)
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said
  #4 (permalink)  
Antiguo 09/02/2012, 14:27
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

estimado zerokilled eso si lo tengo presente pero como el formulario es largo no me sirve de nada si capturan todo y al final no me guarda la informacion por que les falto rellenar algunos de los campos que mensiono
gracias por el comentario.
  #5 (permalink)  
Antiguo 09/02/2012, 14:29
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

mi estimado lukas4 en la funcion que me pondes si mas o menos le entiendo estas haciendo que revise todos los campo de tu formulario y lo que yo necesito es que nada mas revise esos 4 campos que menciono

gracias por la ayuda

otra forma de hacerlo o otra idea
  #6 (permalink)  
Antiguo 09/02/2012, 14:48
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: validar antes de guardar

pues de eso te tienes que encargar tu. si el usuario envio algun dato y es válido según tus criterios, lo que debes hacer es prestarle nuevamente el formulario pero con llenando los campos con la información válida y notificarle la razón del error. obvio, solo guardas la información cuando todo haya validado.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.

Última edición por zerokilled; 09/02/2012 a las 17:54 Razón: error redaccion
  #7 (permalink)  
Antiguo 09/02/2012, 16:54
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

pues entonces puedes poner una función en js o php o en lo que se te antoje que te valide esos campos, pero pues ahí tienes ese ejemplo que te puse si se te complica con los nombres puedes usar un getElementById que es CASI identico al getElementsByName. ejemplo:

Código HTML:
Ver original
  1.     *folio<input type="text" id="folio" name="folio"/>
  2.     nombre<input type="text" name="nombre"/>
  3.     apellido<input type="text" name="apellido"/>
  4.    *id<input type="text" id="id" name="id"/>
  5.    <input type="button" onclick="validar()"/>
  6. </form>
  7. <labe>los campos marcados con un * son obligatorios</label>

y los validas aqui:
Código Javascript:
Ver original
  1. function validar(){
  2.    if(document.getElementById('folio').value==""){
  3.       alert("por favor inserte el numero de folio.");
  4.       return;
  5.    }
  6.    if(document.getElementById("id").value==""){
  7.       alert("por favor inserte el numero de identificación.");
  8.    }
  9. }

Cita:
Iniciado por mexbale Ver Mensaje
Y quisiera que mi formulario antes de mandarlo a guardar checara que esos campos no estén vacíos, que siempre deban de estar llenos, como puedo hacer eso?????
con los ejemplos que te puse puedes validar esos campos
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said
  #8 (permalink)  
Antiguo 14/02/2012, 12:56
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

estimado lukas4 gracias por la ayuda así es como quiero que me quede la validación pero tengo un pequeño problema cuando revisa el formulario si le falta alguno de esos campos me aparece los mensajes correspondientes pero también me borra todo el formulario.

con esta situación como puedo hacerle que no me borre la información????

de antemano te doy las gracias y que tengas un buen dia

saludos
  #9 (permalink)  
Antiguo 14/02/2012, 14:45
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

estimado lukas4 modifique funsion que me pusiste como no me salio con el boton de guardar la voy a validar cuando salgas del campo pero me surgio otro imprevisto si funciona bien pero quisiera que cuando quieran dejar algunos de los campos que mencionamos, que le salga la alerta y que regrese al mismo campo que no puso nada, esta el la funsion que ocupo para que mande alerta que esta vacio


Código Javascript:
Ver original
  1. function validar(){
  2. * *if(document.getElementById('folio').value==""){
  3. * * * alert("por favor inserte el folio.");
  4. * * * return;
  5. * *}
  6. }

y la llama de esta manera
Código HTML:
Ver original
  1. onBlur="validar()"

pero como te comento cuando sale la alerta quisiera que me regresara al mismo campo de donde salio
De antemano te doy las gracias y espero que tengas un buen día

Gracias por tu apoyo

Última edición por mexbale; 14/02/2012 a las 14:51
  #10 (permalink)  
Antiguo 14/02/2012, 19:22
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

que extraño, no deberia de limpiarte el formulario, tal vez tienes mal algo en tu codigo, muestralo para ayudarte =)
En cuanto a lo de regresarse al campo si lo dejan en blanco prueba usando el metodo focus

Código Javascript:
Ver original
  1. function validar(){
  2.    if(document.getElementById('folio').value==""){
  3.       alert("por favor inserte el folio.");
  4.       document.getElementByID('folio').focus();//aqui se debe de regresar al campo vacio
  5.       return;
  6.    }
  7. }
prueba eso y nos comentas =)
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said
  #11 (permalink)  
Antiguo 15/02/2012, 12:03
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

buenos dias lukas4
ok pues si lo hago con el botón queda así todo mi código


Código Javascript:
Ver original
  1. <script>
  2. function validar(){
  3.    if(document.getElementById("folio").value==""){
  4.       alert("por favor inserte el folio.");
  5.    }
  6.    if(document.getElementById("cve_med").value==""){
  7.       alert("por favor inserte clave de medicion.");
  8.    }
  9.    if(document.getElementById("id").value==""){
  10.       alert("por favor inserte el numero de identificación.");
  11.    }
  12.    if(document.getElementById("folio_cer").value==""){
  13.       alert("por favor inserte el folio de certificado.");
  14.    }
  15. }
  16. </script>
Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>pruebas</title>
  5. </head>
  6. <body onkeypress="return pulsar(event)" onLoad="document.formulario.folio.focus()">
  7. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" >
  8. <table width="850" border="1" align="center">
  9.   <tr>
  10.     <td><div align="center">*Folio</div></td>
  11.     <td><div align="center">
  12.       <input type="text" id="folio" name="folio"/>
  13.     </div></td>
  14.   </tr>
  15.   <tr>
  16.     <td><div align="center">*Clave Medicion</div></td>
  17.     <td><div align="center">
  18.       <input type="text" name="cve_med"/>
  19.     </div></td>
  20.   </tr>
  21.   <tr>
  22.     <td><div align="center">Nombre</div></td>
  23.     <td><div align="center">
  24.       <input type="text" name="nombre"/>
  25.     </div></td>
  26.   </tr>
  27.   <tr>
  28.     <td><div align="center">*ID</div></td>
  29.     <td><div align="center">
  30.       <input type="text" id="id" name="id"/>
  31.     </div></td>
  32.   </tr>
  33.   <tr>
  34.     <td><div align="center">*Folio de Certificado</div></td>
  35.     <td><div align="center">
  36.       <input type="text" id="folio_cer" name="folio_cer"/>
  37.     </div></td>
  38.   </tr>
  39.   <tr>
  40.     <td colspan="2">
  41.       <div align="center">
  42.         <input type="submit" name="Guardar" value="Guardar" onclick="validar()" />
  43.         </div></td>
  44.   </tr>
  45. <labe>
  46. <div align="center">los campos marcados con un * son obligatorios
  47.   </label>
  48. </div>
  49. </form>
  50. </body>
  51. </html>
No se en donde esta el error por que cuando le doy en el botón de guardar me borra la información

De antemano te doy las gracias y buen día
  #12 (permalink)  
Antiguo 15/02/2012, 12:09
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

y con respecto a la método focus() si me me queda pero tengo un problema con eso.

como tengo los campos juntos se traba la pagina me muestra la alerta del folio y de la clave de medición te pongo el código que tengo con el método focus()


Código Javascript:
Ver original
  1. <script>
  2. function validar1(){
  3. * *if(document.getElementById("folio").value==""){
  4. * * * alert("por favor inserte el folio.");
  5. * * * document.getElementById("folio").focus();//aqui se debe de regresar al campo vacio
  6. * * * return;
  7. * *}
  8. }
  9. </script>
  10. <script>
  11. function validar2(){
  12. * *if(document.getElementById("cve_med").value==""){
  13. * * * alert("por favor inserte clave de medicion.");
  14. * * * document.getElementById("cve_med").focus();//aqui se debe de regresar al campo vacio
  15. * * * return;
  16. * *}
  17. }
  18. </script>
  19. <script>
  20. function validar3(){
  21. * *if(document.getElementById("id").value==""){
  22. * * * alert("por favor inserte el numero de identificacion.");
  23. * * * document.getElementById("id").focus();//aqui se debe de regresar al campo vacio
  24. * * * return;
  25. * *}
  26. }
  27. </script>
  28. <script>
  29. function validar4(){
  30. * *if(document.getElementById("folio_cer").value==""){
  31. * * * alert("por favor inserte el folio de certificado.");
  32. * * * document.getElementById("folio_cer").focus();//aqui se debe de regresar al campo vacio
  33. * * * return;
  34. * *}
  35. }
  36. </script>
Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>pruebas</title>
  5. </head>
  6. <body onkeypress="return pulsar(event)" onLoad="document.formulario.folio.focus()">
  7. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" >
  8. <table width="850" border="1" align="center">
  9.   <tr>
  10.     <td><div align="center">*Folio</div></td>
  11.     <td><div align="center">
  12.       <input type="text" id="folio" name="folio" onBlur="validar1()"/>
  13.     </div></td>
  14.   </tr>
  15.   <tr>
  16.     <td><div align="center">*Clave Medicion</div></td>
  17.     <td><div align="center">
  18.       <input type="text" name="cve_med" onBlur="validar2()"/>
  19.     </div></td>
  20.   </tr>
  21.   <tr>
  22.     <td><div align="center">Nombre</div></td>
  23.     <td><div align="center">
  24.       <input type="text" name="nombre"/>
  25.     </div></td>
  26.   </tr>
  27.   <tr>
  28.     <td><div align="center">*ID</div></td>
  29.     <td><div align="center">
  30.       <input type="text" id="id" name="id" onBlur="validar3()"/>
  31.     </div></td>
  32.   </tr>
  33.   <tr>
  34.     <td><div align="center">*Folio de Certificado</div></td>
  35.     <td><div align="center">
  36.       <input type="text" id="folio_cer" name="folio_cer" onBlur="validar4()"/>
  37.     </div></td>
  38.   </tr>
  39.   <tr>
  40.     <td colspan="2">
  41.       <div align="center">
  42.         <input type="submit" name="Guardar" value="Guardar" />
  43.         </div></td>
  44.   </tr>
  45. <labe>
  46. <div align="center">los campos marcados con un * son obligatorios
  47.   </label>
  48. </div>
  49. </form>
  50. </body>
  51. </html>

Espero que me puedas ayudar de cualquier manera con este problema

te doy las gracias por el tiempo que te tomas para revisar el tema

suerte buen día
  #13 (permalink)  
Antiguo 16/02/2012, 11:26
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

trata cambiando el boton, en lugar de submit ponle button creo que eso es parte del problema y al codigo js le agregas unas lineas:

Código Javascript:
Ver original
  1. function validar(){
  2. * *if(document.getElementById("folio").value==""){
  3. * * * alert("por favor inserte el folio.");
  4.       return;
  5. * *}
  6. * *if(document.getElementById("cve_med").value==""){
  7. * * * alert("por favor inserte clave de medicion.");
  8.       return;
  9. * *}
  10. * *if(document.getElementById("id").value==""){
  11. * * * alert("por favor inserte el numero de identificación.");
  12.       return;
  13. * *}
  14. * *if(document.getElementById("folio_cer").value==""){
  15. * * * alert("por favor inserte el folio de certificado.");
  16.       return;
  17. * *}
  18.    document.getElementById("formulario").submit();
  19. }

tambien estaba revisando unas validaciones en w3school, y encontre este ejemplo click aqui

porias agregarle a tu form el atributo onsubmit como lo muestra el ejemplo y quitarle al submit el atributo onclick

Código HTML:
Ver original
  1. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post"  onsubmit="return validar()">
  2. <input type="submit" name="Guardar" value="Guardar" />

y a tu codigo js agregale en los ifs el return false y si quieres de una vez agregale el focus

Código Javascript:
Ver original
  1. <script>
  2. function validar(){
  3. * *if(document.getElementById("folio").value==""){
  4. * * * alert("por favor inserte el folio.");
  5.       document.getElementById("folio").focus();
  6.       return false;
  7. * *}
  8. * *if(document.getElementById("cve_med").value==""){
  9. * * * alert("por favor inserte clave de medicion.");
  10.       document.getElementById("cve_med").focus();
  11.       return false;
  12. * *}
  13. * *if(document.getElementById("id").value==""){
  14. * * * alert("por favor inserte el numero de identificación.");
  15.       document.getElementById("id").focus();
  16.       return false;
  17. * *}
  18. * *if(document.getElementById("folio_cer").value==""){
  19. * * * alert("por favor inserte el folio de certificado.");
  20.       document.getElementById("folio_cer").focus();
  21.       return false;
  22. * *}
  23. }
  24. </script>
en el Clave de medicion te falto ponerle el id.

trata con alguna de estas ideas para ver si te funciona.

otra cosa, como estas usando tablas creo que esta demas que en cada td pongas un div yo recomendaria que aprendieras a usar divs+css (es un poco tedioso cuando uno esta aprendiendo, pero luego se pone divertido) pero por mientras sigue utilizando la tabla, ya cuando te sientas comodo trata de cambiar las tablas por divs.

tambien trata de anidar bien las etiquetas en las lineas 47 a la 50 tienes mal cerrado el label y el div:
Código HTML:
Ver original
  1. <labe> <!-- le falta la L al final -->
  2. <div align="center">los campos marcados con un * son obligatorios
  3.   </label> <!-- debes cerrar primero el div y al final el label -->
  4. </div>

saludos y buen dia
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said

Última edición por lukas4; 16/02/2012 a las 11:30 Razón: me falto ponerle ; a los return
  #14 (permalink)  
Antiguo 16/02/2012, 16:21
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

Estimado lukas4 la primera opción que me poner si me funciona me manda el alerta cuando no lleno los campo y no me borra la información, pero cuando ya lleno todos los campos y le doy guardar no me guarda nada en mi base de datos el código quedo así:


Código Javascript:
Ver original
  1. <script>
  2. function validar(){
  3.    if(document.getElementById("folio").value==""){
  4.       alert("por favor inserte el folio.");
  5. * * * document.getElementById("folio").focus();
  6. * * * return false;
  7.    }
  8.    if(document.getElementById("cve_med").value==""){
  9.       alert("por favor inserte clave de medicion.");
  10. * * * document.getElementById("cve_med").focus();
  11. * * * return false;
  12.    }
  13.    if(document.getElementById("id").value==""){
  14.       alert("por favor inserte el numero de identificación.");
  15. * * * document.getElementById("id").focus();
  16. * * * return false;
  17.    }
  18.    if(document.getElementById("folio_cer").value==""){
  19.       alert("por favor inserte el folio de certificado.");
  20. * * * document.getElementById("folio_cer").focus();
  21. * * * return false;
  22.    }
  23.    document.getElementById("formulario").submit();
  24. }
  25. </script>
Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>pruebas</title>
  5. </head>
  6. <body onkeypress="return pulsar(event)" onLoad="document.formulario.FOLIO.focus()">
  7. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" >
  8. <table width="850" border="1" align="center">
  9.   <tr>
  10.     <td><div align="center">*Folio</div></td>
  11.     <td><div align="center">
  12.       <input type="text" id="FOLIO" name="FOLIO" size="8" maxlength="8"/>
  13.     </div></td>
  14.   </tr>
  15.   <tr>
  16.     <td><div align="center">*Clave Medicion</div></td>
  17.     <td><div align="center">
  18.       <input type="text" id="CVE_MED" name="CVE_MED" size="2" maxlength="2"/>
  19.     </div></td>
  20.   </tr>
  21.   <tr>
  22.     <td><div align="center">Nombre</div></td>
  23.     <td><div align="center">
  24.       <input type="text" id="NOMBRE" name="NOMBRE"/>
  25.     </div></td>
  26.   </tr>
  27.   <tr>
  28.     <td><div align="center">*ID</div></td>
  29.     <td><div align="center">
  30.       <input type="text" id="ID" name="ID" size="2" maxlength="2"/>
  31.     </div></td>
  32.   </tr>
  33.   <tr>
  34.     <td><div align="center">*Folio de Certificado</div></td>
  35.     <td><div align="center">
  36.       <input type="text" id="FOLIO_CER" name="FOLIO_CER" size="9" maxlength="9"/>
  37.     </div></td>
  38.   </tr>
  39.   <tr>
  40.     <td colspan="2">
  41.       <div align="center">
  42.         <input type="button" name="Guardar" value="Guardar" onClick="validar()" />
  43.         </div></td>
  44.   </tr>
  45. <label><div align="center">los campos marcados con un * son obligatorios</div></label>
  46. </form>
  47. </body>
  48. </html>

no se en que estoy mal y por que no me guarda

no se si podrías checarlo y decirme en que estoy mal o cual es mi error

de antemano te doy las gracias
  #15 (permalink)  
Antiguo 16/02/2012, 16:48
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

la verdad yo no estoy familiarizado con el uso de $_SERVER['PHP_SELF'] pero si quieres mandar datos a una BD ocupamos ver tu codigo php, y en tu codigo no veo ningun include ni nada por el estilo que haga la llamada a un archivo php.

cambia el method="post" a method="get" y revisa la barra de direcciones para ver si te esta enviando los parametros a la nueva pagina o en tu caso, esta misma. deberias ver algo asi:

pagina.php?valor1=talCosa&valor2=talOtraCosa
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said
  #16 (permalink)  
Antiguo 20/02/2012, 11:46
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

ok pues bueno te voy a poner todo mi código que tengo en la pagina:

Código HTML:
Ver original
  1. <?PHP  //primera Tabla
  2. if(isset($_POST["Guardar"]))
  3. {
  4.  
  5. $FOLIO = $_POST['FOLIO'] = trim($_POST['FOLIO']);
  6. $CVE_MED = $_POST['CVE_MED'] = trim($_POST['CVE_MED']);
  7. $NOMBRE = $_POST['NOMBRE'] = trim($_POST['NOMBRE']);
  8. if (empty($ID)){$ID='NULL';}
  9. $FOLIO_CER = $_POST['FOLIO_CER'] = trim($_POST['FOLIO_CER']);
  10.  
  11. // Paso 1: Recibimos el formulario:
  12. $FOLIO = $_POST['FOLIO'] = trim($_POST['FOLIO']);
  13. mysql_connect("localhost", "root", "*******");
  14. mysql_select_db("PRONTO");
  15.  
  16. mysql_query ("INSERT INTO
  17. prueba (FOLIO, CVE_MED, NOMBRE, ID, FOLIO_CER, FECHA)
  18. VALUES('$FOLIO', '$CVE_MED', '$NOMBRE', $ID, '$FOLIO_CER',  NOW())", mysql_connect(localhost , root , ********));
  19.  
  20. }
  21. ?>
  22. function validar(){
  23.    if(document.getElementById("folio").value==""){
  24.       alert("por favor inserte el folio.");
  25. * * * document.getElementById("folio").focus();
  26. * * * return false;
  27.    }
  28.    if(document.getElementById("cve_med").value==""){
  29.       alert("por favor inserte clave de medicion.");
  30. * * * document.getElementById("cve_med").focus();
  31. * * * return false;
  32.    }
  33.    if(document.getElementById("id").value==""){
  34.       alert("por favor inserte el numero de identificación.");
  35. * * * document.getElementById("id").focus();
  36. * * * return false;
  37.    }
  38.    if(document.getElementById("folio_cer").value==""){
  39.       alert("por favor inserte el folio de certificado.");
  40. * * * document.getElementById("folio_cer").focus();
  41. * * * return false;
  42.    }
  43.    document.getElementById("formulario").submit();
  44. }
  45. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  46. <html xmlns="http://www.w3.org/1999/xhtml">
  47. <script type="text/javascript">
  48. function mostrarTab(obj) {
  49.     rolling=obj.scrollTop;
  50.     if(typeof obj.selectionStart == 'number') {
  51.         // Resto de navegadores
  52.         var start = obj.selectionStart;
  53.         var end = obj.selectionEnd;
  54.         obj.value = obj.value.substring(0, start)+"\t";
  55.         obj.value+= obj.value.substring(start, obj.value.length);
  56.         obj.focus();
  57.         obj.selectionStart =  obj.selectionEnd= end + 2;
  58.     }
  59.     else if(document.selection) {
  60.         // Internet Explorer
  61.         obj.focus();
  62.         var range = document.selection.createRange();
  63.         if(range.parentElement() != obj) return false;
  64.         if (range.text != "") {
  65.             if(typeof range.text == 'string'){
  66.                 document.selection.createRange().text ="\t"+range.text;
  67.             }
  68.             else obj.value += "\t";
  69.         }
  70.         else
  71.             obj.value += "\t";
  72.     }
  73.     obj.scrollTop=rolling;
  74. }
  75. function tabulador(form,field)
  76. {
  77. var next=0, found=false
  78. var f=form
  79. //if(event.keyCode!=13) return;
  80. for(var i=0;i<f.length;i++) {
  81.     if(field.name==f.item(i).name){
  82.         next=i+1;
  83.         found=true
  84.         break;
  85.     }
  86. }
  87. //MODIFICACION A LA FUNCION &&  f.item(next).style.display!='none'
  88. while(found){
  89.     if( f.item(next).disabled==false &&  f.item(next).type!='hidden' &&  f.item(next).style.display!='none'){
  90.         f.item(next).focus();
  91.         break;
  92.     }
  93.     else{
  94.         if(next<f.length-1)
  95.             next=next+1;
  96.         else
  97.             break;
  98.     }
  99. }
  100. }
  101. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  102. <title>pruebas</title>
  103. </head>
  104. <body onkeypress="return pulsar(event)" onLoad="document.formulario.FOLIO.focus()">
  105. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" >
  106. <table width="850" border="1" align="center">
  107.   <tr>
  108.     <td><div align="center">*Folio</div></td>
  109.     <td><div align="center">
  110.       <input type="text" id="FOLIO" name="FOLIO" size="8" maxlength="8" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  111.     </div></td>
  112.   </tr>
  113.   <tr>
  114.     <td><div align="center">*Clave Medicion</div></td>
  115.     <td><div align="center">
  116.       <input type="text" id="CVE_MED" name="CVE_MED" size="2" maxlength="2" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  117.     </div></td>
  118.   </tr>
  119.   <tr>
  120.     <td><div align="center">Nombre</div></td>
  121.     <td><div align="center">
  122.       <input type="text" id="NOMBRE" name="NOMBRE" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  123.     </div></td>
  124.   </tr>
  125.   <tr>
  126.     <td><div align="center">*ID</div></td>
  127.     <td><div align="center">
  128.       <input type="text" id="ID" name="ID" size="2" maxlength="2" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  129.     </div></td>
  130.   </tr>
  131.   <tr>
  132.     <td><div align="center">*Folio de Certificado</div></td>
  133.     <td><div align="center">
  134.       <input type="text" id="FOLIO_CER" name="FOLIO_CER" size="9" maxlength="9" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  135.     </div></td>
  136.   </tr>
  137.   <tr>
  138.     <td colspan="2">
  139.       <div align="center">
  140.         <input type="button" name="Guardar" value="Guardar" onClick="validar()" />
  141.         </div></td>
  142.   </tr>
  143. <label><div align="center">los campos marcados con un * son obligatorios</div></label>
  144. </form>
  145. </body>
  146. </html>

como podrás ver todo lo hago en una sola pagina, al parecer el único conflicto que tengo con el código es, le cambio el tipo del botón lo tenia como submit y así si me guarda pero no me hace la validación con respecto a los campos ya mencionados, pero cuando le pongo al botón tipo Button me hace la validación pero no me guarda
espero que enconchemos el error

de antemano te mando las gracias y que tengas una buena tarde

saludos y suerte
  #17 (permalink)  
Antiguo 21/02/2012, 12:35
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

pues parece ser que la variable $_POST['Guardar'] viene vacia, por eso no te esta guardando nada, igual podrias cambiar la validacion usando los campos de folio,cve_med o id.

o si no, podemos cambiar el codigo poquito otra vez. a tu form agregale el atributo onsubmit:

Código HTML:
Ver original
  1. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" onsubmit="return validar()">

y el boton cambialo por un submit
Código HTML:
Ver original
  1. <input type="button" name="Guardar" value="Guardar" />
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said
  #18 (permalink)  
Antiguo 21/02/2012, 16:58
Avatar de mexbale  
Fecha de Ingreso: septiembre-2010
Ubicación: Iztapalapa
Mensajes: 146
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: validar antes de guardar

ok gracias lukas4 ya funciona la validación y guarda perfectamente quedo así:


Código HTML:
Ver original
  1. <?PHP  //primera Tabla
  2. if(isset($_POST["Guardar"]))
  3. {
  4.  
  5. $FOLIO = $_POST['FOLIO'] = trim($_POST['FOLIO']);
  6. $CVE_MED = $_POST['CVE_MED'] = trim($_POST['CVE_MED']);
  7. $NOMBRE = $_POST['NOMBRE'] = trim($_POST['NOMBRE']);
  8. if (empty($ID)){$ID='NULL';}
  9. $FOLIO_CER = $_POST['FOLIO_CER'] = trim($_POST['FOLIO_CER']);
  10.  
  11. // Paso 1: Recibimos el formulario:
  12. $FOLIO = $_POST['FOLIO'] = trim($_POST['FOLIO']);
  13. mysql_connect("localhost", "root", "******");
  14. mysql_select_db("PRONTO");
  15.  
  16. mysql_query ("INSERT INTO
  17. prueba (FOLIO, CVE_MED, NOMBRE, ID, FOLIO_CER, FECHA)
  18. VALUES('$FOLIO', '$CVE_MED', '$NOMBRE', $ID, '$FOLIO_CER',  NOW())", mysql_connect(localhost , root , ******));
  19.  
  20. }
  21. ?>
  22. function validar(){
  23.    if(document.getElementById("folio").value==""){
  24.       alert("por favor inserte el folio.");
  25. * * * document.getElementById("folio").focus();
  26. * * * return false;
  27.    }
  28.    if(document.getElementById("cve_med").value==""){
  29.       alert("por favor inserte clave de medicion.");
  30. * * * document.getElementById("cve_med").focus();
  31. * * * return false;
  32.    }
  33.    if(document.getElementById("id").value==""){
  34.       alert("por favor inserte el numero de identificación.");
  35. * * * document.getElementById("id").focus();
  36. * * * return false;
  37.    }
  38.    if(document.getElementById("folio_cer").value==""){
  39.       alert("por favor inserte el folio de certificado.");
  40. * * * document.getElementById("folio_cer").focus();
  41. * * * return false;
  42.    }
  43.    document.getElementById("formulario").submit();
  44. }
  45. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  46. <html xmlns="http://www.w3.org/1999/xhtml">
  47. <script type="text/javascript">
  48. function mostrarTab(obj) {
  49.     rolling=obj.scrollTop;
  50.     if(typeof obj.selectionStart == 'number') {
  51.         // Resto de navegadores
  52.         var start = obj.selectionStart;
  53.         var end = obj.selectionEnd;
  54.         obj.value = obj.value.substring(0, start)+"\t";
  55.         obj.value+= obj.value.substring(start, obj.value.length);
  56.         obj.focus();
  57.         obj.selectionStart =  obj.selectionEnd= end + 2;
  58.     }
  59.     else if(document.selection) {
  60.         // Internet Explorer
  61.         obj.focus();
  62.         var range = document.selection.createRange();
  63.         if(range.parentElement() != obj) return false;
  64.         if (range.text != "") {
  65.             if(typeof range.text == 'string'){
  66.                 document.selection.createRange().text ="\t"+range.text;
  67.             }
  68.             else obj.value += "\t";
  69.         }
  70.         else
  71.             obj.value += "\t";
  72.     }
  73.     obj.scrollTop=rolling;
  74. }
  75. function tabulador(form,field)
  76. {
  77. var next=0, found=false
  78. var f=form
  79. //if(event.keyCode!=13) return;
  80. for(var i=0;i<f.length;i++) {
  81.     if(field.name==f.item(i).name){
  82.         next=i+1;
  83.         found=true
  84.         break;
  85.     }
  86. }
  87. //MODIFICACION A LA FUNCION &&  f.item(next).style.display!='none'
  88. while(found){
  89.     if( f.item(next).disabled==false &&  f.item(next).type!='hidden' &&  f.item(next).style.display!='none'){
  90.         f.item(next).focus();
  91.         break;
  92.     }
  93.     else{
  94.         if(next<f.length-1)
  95.             next=next+1;
  96.         else
  97.             break;
  98.     }
  99. }
  100. }
  101. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  102. <title>pruebas</title>
  103. </head>
  104. <body onkeypress="return pulsar(event)" onLoad="document.formulario.FOLIO.focus()">
  105. <form name="formulario" id="formulario" action="<?=$_SERVER['PHP_SELF']?>" method="post" onSubmit="return validar()">
  106. <table width="850" border="1" align="center">
  107.   <tr>
  108.     <td><div align="center">*Folio</div></td>
  109.     <td><div align="center">
  110.       <input type="text" id="FOLIO" name="FOLIO" size="8" maxlength="8" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  111.     </div></td>
  112.   </tr>
  113.   <tr>
  114.     <td><div align="center">*Clave Medicion</div></td>
  115.     <td><div align="center">
  116.       <input type="text" id="CVE_MED" name="CVE_MED" size="2" maxlength="2" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  117.     </div></td>
  118.   </tr>
  119.   <tr>
  120.     <td><div align="center">Nombre</div></td>
  121.     <td><div align="center">
  122.       <input type="text" id="NOMBRE" name="NOMBRE" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  123.     </div></td>
  124.   </tr>
  125.   <tr>
  126.     <td><div align="center">*ID</div></td>
  127.     <td><div align="center">
  128.       <input type="text" id="ID" name="ID" size="2" maxlength="2" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  129.     </div></td>
  130.   </tr>
  131.   <tr>
  132.     <td><div align="center">*Folio de Certificado</div></td>
  133.     <td><div align="center">
  134.       <input type="text" id="FOLIO_CER" name="FOLIO_CER" size="9" maxlength="9" onkeyup = "this.value=this.value.toUpperCase();if (this.value.length == this.getAttribute('maxlength')){tabulador(this.form,this)}"/>
  135.     </div></td>
  136.   </tr>
  137.   <tr>
  138.     <td colspan="2">
  139.       <div align="center">
  140.         <input type="submit" name="Guardar" value="Guardar" />
  141.         </div></td>
  142.   </tr>
  143. <label><div align="center">los campos marcados con un * son obligatorios</div></label>
  144. </form>
  145. </body>
  146. </html>

Muchas gracias por tu ayuda que tengas una buena tarde
  #19 (permalink)  
Antiguo 21/02/2012, 23:10
Avatar de lukas4  
Fecha de Ingreso: octubre-2008
Ubicación: frente al pc
Mensajes: 496
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: validar antes de guardar

excelente, un gusto haber podido ayudar
__________________
http://situcomo.blogspot.com
Karma is a Bitch... they said

Etiquetas: formulario
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 01:24.