Foros del Web » Programando para Internet » Javascript »

Validacion caracteres y Enter

Estas en el tema de Validacion caracteres y Enter en el foro de Javascript en Foros del Web. Hola, tengo un codigo que valida un campo de texto. Lo hace bien pero si presiono enter no lo valida. ¿Como puedo añadirle ese evento? ...
  #1 (permalink)  
Antiguo 22/03/2006, 13:44
 
Fecha de Ingreso: marzo-2004
Mensajes: 81
Antigüedad: 20 años
Puntos: 0
Validacion caracteres y Enter

Hola, tengo un codigo que valida un campo de texto. Lo hace bien pero si presiono enter no lo valida.
¿Como puedo añadirle ese evento?

Código HTML:
  var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóú. 1234567890?¿,-@€$";
  var checkStr = formulario.texto.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
	ch = checkStr.charAt(i);
	for (j = 0;  j < checkOK.length;  j++)
	  if (ch == checkOK.charAt(j))
		break;
	if (j == checkOK.length)
	{
	  allValid = false;
	  break;
	}
  }
  if (!allValid)
  {
	 alert('Caracteres inválidos en el campo \"Texto\".');
	 formulario.texto.focus();
	 return false;
  }
  #2 (permalink)  
Antiguo 23/03/2006, 02:59
Avatar de uamistad  
Fecha de Ingreso: diciembre-2004
Ubicación: Cd. de México
Mensajes: 1.395
Antigüedad: 19 años, 4 meses
Puntos: 1
Cita:
¿cómo puedo añadirle ese evento
Mete todo dentro de una función (yo le llamé validar()) y llámala con el evento onSubmit()

Código HTML:
//
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> <head> <title>Prueba</title>  

    <script>
    function validar(){
      var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóú. 1234567890?¿,-@€$";
      var checkStr = formulario.texto.value;
      var allValid = true;
      for (i = 0;  i < checkStr.length;  i++)
      {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
          if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length)
        {
          allValid = false;
          break;
        }
      }
      if (!allValid)
      {
         alert('Caracteres inválidos en el campo \"Texto\".');
         formulario.texto.focus();
         return false;
      }
    }//end function validar
    </script>

</head>
<body>

<form name="formulario" onSubmit="return validar()">
    <input type="text" name="texto">
    <input type="submit" value="Enviar">
</form>

</body> 
</html> 
y aquí un código más optimizado (comentado; si viola alguna regla, regresa al input y selecciona el texto haciendo más fácil su edición; detecta caracteres vacíos; hace uso de getElementById que es una forma más sencilla de accesar a los elementos del formulario y en general del DOM):

Código HTML:
//
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> <head> <title>Prueba</title>  

    <script>
    function validar(){
      //declaraciones de variables y expresiones regulares    
      var valida = new RegExp("^[\\wáéíóúñÁÉÍÓÚÑ\.?¿,@€\$ -]+$");
      var textoInput = document.getElementById("texto");
      var formulario = document.getElementById("formulario");

      //si el texto está vacío, muestra mensaje
      if(textoInput.value.length < 1){
          alert('El campo de texto está vacío.');
          textoInput.focus();
          textoInput.select();
          return false;
          }

      //si no está vacío, quizá tenga caracateres inválidos
      if(!valida.test(textoInput.value)){
          alert('Tienes caracteres inválidos.');
          textoInput.focus();
          textoInput.select();
          return false;
          }

      //si llegamos a este punto, es que todo está en orden
      return true;

    }//end function validar
    </script>

</head>
<body>

<form onSubmit="return validar()" id="formulario">
    <input type="text" id="texto">
    <input type="submit" value="Enviar">
</form>

</body> 
</html> 
buena suerte !
__________________
"Di no al Internet Explorer" -Proverbio Chino-
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 04:44.