Foros del Web » Programando para Internet » Javascript »

[SOLUCIONADO] Error validación de formulario

Estas en el tema de Error validación de formulario en el foro de Javascript en Foros del Web. Buenas, tengo un problema con la validación de un formulario. Al comprobar si el script funciona he dejado todos los campos obligatorios en blanco y ...
  #1 (permalink)  
Antiguo 24/03/2013, 12:33
Avatar de temerariomalaga  
Fecha de Ingreso: marzo-2013
Ubicación: Londres
Mensajes: 156
Antigüedad: 11 años, 1 mes
Puntos: 9
Error validación de formulario

Buenas, tengo un problema con la validación de un formulario. Al comprobar si el script funciona he dejado todos los campos obligatorios en blanco y el formulario pasa, no me sale ningún mensaje de error.
El código del script encargado de realizar la validación es el siguiente:
Código:
<script language="JavaScript">
		function validacion(){
			nombre = document.getElementById("nombre").value;
			email = document.getElementById("email").value;
			asunto = document.getElementById("asunto").value;
			mensaje = document.getElementById("mensaje").value;
			if(nombre==null || nombre.lenght==0 || /^\s+$/.test(nombre)){
				alert('[ERROR] El campo nombre está incompleto'); return false;
			}
			else if(!(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)/.test(email)) ){
				alert('[ERROR] La dirección de email no es válida'); return false;
			}
			else if(asunto==null || asunto.lenght==0 || /^\s+$/.test(asunto)){
				alert('[ERROR] El campo asunto está incompleto'); return false;
			}
			else if(mensaje==null || mensaje.lenght==0 || /^\s+$/.test(mensaje)){
				alert('[ERROR] No ha introducido ningún mensaje'); return false;
			}
			return true;
		}
	</script>
el script se ejecuta con el evento onsubmit="return validacion()" dentro del formulario.
¿Alguien sabe por qué no funciona mi script?
Gracias de antemano
__________________
Málaga Club de Fútbol: Memoria, Compromiso, Fe
  #2 (permalink)  
Antiguo 24/03/2013, 13:09
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Error validación de formulario

el nombre de la propiedad es length no lenght
Además la expresión regular para email tiene un fallo
Código:
<script type="text/javascript">
		function validacion(){
			nombre = document.getElementById("nombre").value;
			email = document.getElementById("email").value;
			asunto = document.getElementById("asunto").value;
			mensaje = document.getElementById("mensaje").value;
			var formato = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			if(nombre.length==0){
				alert('[ERROR] El campo nombre está incompleto'); return false;
			}
			else if(!(formato.test(email)) ){
				alert('[ERROR] La dirección de email no es válida'); return false;
			}
			else if(asunto==null || asunto.length==0 || /^\s+$/.test(asunto)){
				alert('[ERROR] El campo asunto está incompleto'); return false;
			}
			else if(mensaje==null || mensaje.length==0 || /^\s+$/.test(mensaje)){
				alert('[ERROR] No ha introducido ningún mensaje'); return false;
			}
			return true;
		}
	</script>
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #3 (permalink)  
Antiguo 24/03/2013, 13:36
Avatar de temerariomalaga  
Fecha de Ingreso: marzo-2013
Ubicación: Londres
Mensajes: 156
Antigüedad: 11 años, 1 mes
Puntos: 9
Respuesta: Error validación de formulario

Gracias por la respuesta, lo he probado de nuevo y sigue sin funcionar, este formulario está siendo un desastre porque ni se valida ni se envia
dejo aqui el codigo entero de la web por si el fallo se encuentra en otra parte.
Código HTML:
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/html4/loose.dtd">
<html>
<head>
	<title>Contacto - Representaciones Jesús Suviri</title>
	<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" >
	<meta name="author" content="Abel Suviri">
	<meta name="keywords" content="baño, ducha, grifo, mampara, representaciones, suviri">
	<link rel="stylesheet" type="text/css" href="style.css">
	<script type="text/javascript">
		function validacion(){
			nombre = document.getElementById("nombre").value;
			email = document.getElementById("email").value;
			asunto = document.getElementById("asunto").value;
			mensaje = document.getElementById("mensaje").value;
			var formato = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			if(nombre==null || nombre.length==0 || /^\s+$/.test(nombre)){
				alert('[ERROR] El campo nombre está incompleto'); return false;
			}
			else if(!(formato.test(email)){
				alert('[ERROR] La dirección de email no es válida'); return false;
			}
			else if(asunto==null || asunto.length==0 || /^\s+$/.test(asunto)){
				alert('[ERROR] El campo asunto está incompleto'); return false;
			}
			else if(mensaje==null || mensaje.length==0 || /^\s+$/.test(mensaje)){
				alert('[ERROR] No ha introducido ningún mensaje'); return false;
			}
			return true;
		}
	</script>	
</head>
<body>
<div id="banner">
		<img src="images/banner.gif"></img>
	</div>
	<div id="menu">
		<ul>
			<li><a href="index.html">inicio</a>
			<li><a href="firmas.html">firmas</a>
			<li><a href="productos.html">productos</a>
			<li><a href="descargas.html">descargas</a>
			<li><a href="contacto.html">contacto</a>
		</ul>
	</div>	
	<div id="contacto">
		<h1>Jesús Suviri</h1>
		Telf. 610 725 255<br>
		Fax. 952 411 242<br>
		Mail: [email protected]<br>
		MÁLAGA
	</div>	
	<hr>
	<div id="formulario">
		<p>Puede contactar también rellenando el siguiente formulario con los datos solicitados.</p>
		<form name="formulario" action="envio.php" method="post" onsubmit="return validacion()">
			<table>
				<tr>
					<td>Nombre:</td>
					<td><input type="text" name="nombre" id="nombre" value="" size="50"/></td>
				</tr>
				<tr>
					<td>E-mail:</td>
					<td> <input type="text" name="email" id="email" value="" size="50"/></td>
				</tr>
				<tr>
					<td>Asunto:</td>
					<td><input type="text" name="asunto" id="asunto" value="" size="50"/></td>
				</tr>
				<tr>
					<td>Introduzca su mensaje:</td>
					<td><textarea cols="30" rows="10" ></textarea></td>	
				</tr>
				<tr>
					<td><input type="submit" value="Enviar"/><input type="reset" value="Limpiar"/></td>
				</tr>
			</table>
		</form>
	</div>	
	<div id="copyright">
	Diseñado por Abel Suviri ([email protected]) 
	</div>
</body>
</html> 
__________________
Málaga Club de Fútbol: Memoria, Compromiso, Fe
  #4 (permalink)  
Antiguo 24/03/2013, 15:23
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Error validación de formulario

A ver vamos a ordenarlo un poco, hay varias formas de hacer esto

Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <title>titulo</title>
  5. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  6.  
  7. <style type="text/css">
  8. /*<![CDATA[*/
  9.  
  10. label{
  11. width: 150px;
  12. display: inline-block;
  13. }
  14.  
  15. /*]]>*/
  16. <script type="text/javascript">
  17.  
  18. function validar(){
  19.     // menos el de email. limpiamos los campos con la funcion limpiar()
  20. var nombre = limpiar(document.getElementById('nombre').value);
  21. var email = document.getElementById('email').value;
  22. var asunto = limpiar(document.getElementById('asunto').value);
  23. var mensaje = limpiar(document.getElementById('mensaje').value);
  24. var formato = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; // expresion para validar email
  25.  
  26. if(nombre == ""){
  27. alert('Ingrese su nombre')
  28. return false; // devolvés false si hay error
  29. }
  30. var v_email = formato.test(email);
  31.  
  32. if((v_email != true)||(email == "")){ // test() devuelve true solo si se verifica la regExp
  33. alert('Email no válido');
  34. return false;
  35. }
  36.  
  37. if(asunto == ""){
  38. alert('Ingrese el asunto')
  39. return false;
  40. }
  41.  
  42. if(mensaje == ""){
  43. alert('Ingrese el mensaje')
  44. return false;
  45. }
  46.  
  47.  
  48. /// Si no hubo ningún error, el form se procesa y se envía aal action del form
  49.  
  50. alert('gracias ' + nombre);
  51.  
  52. }
  53.  
  54.  
  55. function limpiar(valor){
  56. var valor_campo = valor.replace(/^\s+/g,'').replace(/\s+$/g,'');// limpias espacios en blanco al inicio y final del nombre
  57. return valor_campo;
  58. }
  59.  
  60. </script>
  61. </head>
  62. <div>
  63. <form action="#" onsubmit="return validar();">
  64. <label for="nombre">Nombre: </label><input type="text" value="" id="nombre" name="nombre" /><br />
  65. <label for="email">Email: </label><input type="text" value="" id="email" name="email" /><br />
  66. <label for="asunto">Asunto: </label><input type="text" id="asunto" name="asunto" /><br />
  67. <label for="mensaje">Mensaje: </label><input type="text" id="mensaje" name="mensaje" /><br />
  68. <input type="submit" value="enviar" />
  69. </form>
  70. </div>
  71. </body>
  72. </html>

Asi te debería funcionar
Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #5 (permalink)  
Antiguo 25/03/2013, 10:21
Avatar de temerariomalaga  
Fecha de Ingreso: marzo-2013
Ubicación: Londres
Mensajes: 156
Antigüedad: 11 años, 1 mes
Puntos: 9
Respuesta: Error validación de formulario

Muchas gracias, ya me funciona perfectamente el script, ahora solo me hace falta que funcione el php, muchas gracias compi
__________________
Málaga Club de Fútbol: Memoria, Compromiso, Fe

Etiquetas: campos, formulario, funcion
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 20:53.