Ver Mensaje Individual
  #2 (permalink)  
Antiguo 23/03/2006, 02:59
Avatar de uamistad
uamistad
 
Fecha de Ingreso: diciembre-2004
Ubicación: Cd. de México
Mensajes: 1.395
Antigüedad: 19 años, 5 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-