Error validating a form with JavaScript when you press a key or lose focus

1

I am trying to put a validation on the client side of some forms on my web page, even adding a class to show the error, or I have already added a document.write due to desperation.

Such is the thing that these would be my validations and this my code. I do not know where I have the fault:

$(document).ready(function() {
  //variables globales
  var acronimo = $("#acronimo");
  var categoria = $("#categoria");

});

//funciones de validación

function validateAcronimo() {
  //No cumple longitud máxima-minima
  if (acronimo.val().length <= 4) {
    acronimo.addClass("error");
    document.write("Prueba");
    return false;
  }
  //Si lognitud pero no caracteres
  else if (!acronimo.val().match(/^[A-Z]+$/)) {
    acronimo.addClass("error");
    return false;
  }
  //Si longitud, si caracteres
  else {
    acronimo.removeClass("error");
    return false;
  }
}

function validateCategoria() {
  //Longitud máxima
  if (categoria.val().length <= 50) {
    categoria.addClass("error");
    return false;
  }
  //Si
  else {
    categoria.removeClass("error");
    return false;
  }
}

//Perdida de foco
acronimo.blur(validateAcronimo);
categoria.blur(validateCategoria);

//Pulsacion de tecla
acronimo.keyup(validateAcronimo);
categoria.keyup(validateCategoria);
// Envio de formulario  
$("#form1").submit(function() {
  if (validateAcronimo() & validateCategoria())
    return true;
  else
    return false;
});
<script src="https://code.jquery.com/jquery-3.2.0.js"></script>

<form id="form1 " action="?action=<?php echo isset($obj_categoria) ? 'actualizar' : 'registrar'; ?>" method="POST" style="margin-bottom:30px;">
  <input type="hidden" name="id" value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('acronimo') : ''; ?>" />

  <table style="width:500px;">
    <tr>
      <th style="text-align:left;">Acronimo</th>
      <td><input id="acronimo" class="requisites" type="text" name="acronimo" value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('acronimo') : ''; ?>" style="width:100%;" required /></td>

      <th style="text-align:left;">Categoria</th>
      <td><input id="categoria" class="requisites" type="text" name="categoria" value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('categoria') : ''; ?>" style="width:100%;" required/></td>
    </tr>
    <tr>
      <td colspan="2"><button type="submit" class="btn btn-success">Guardar</button></td>
      <td colspan="2">
        <form action="index.php">
          <input class="btn btn-primary" type="reset" value="Limpiar" />
        </form>
      </td>
    </tr>
  </table>
</form>
    
asked by Alberto Cepero de Andrés 09.05.2017 в 09:32
source

2 answers

2

You have several failures:

  • The form is called form1 and you have it with space
  • You are not recognizing the "global variables" so the events are not thrown
  • In your checks you never return true
  • Notes:

    • I think the category has the wrong check, would not it be fine if it's less than 50 characters?
    • I added the css of the error class that you did not put (a red background, for example)

    • Please note that acronyms do not necessarily have to go in all caps, to difference of acronyms.

    var acronimo = $("#acronimo");
    var categoria = $("#categoria");
    
    
    //funciones de validación
    
    function validateAcronimo() {
      //No cumple longitud máxima-minima
      if (acronimo.val().length <= 4) {
        acronimo.addClass("error");
        //document.write("Prueba");
        return false;
      } else {
    
        //Si lognitud pero no caracteres
        if (!acronimo.val().match(/^[A-Z]+$/)) {
          acronimo.addClass("error");
          return false;
        }
        //Si longitud, si caracteres
        else {
          acronimo.removeClass("error");
          return true;
        }
      }
    
    }
    
    function validateCategoria() {
      //Longitud máxima
      if (categoria.val().length <= 50) {
        categoria.addClass("error");
        return false;
      }
      //Si
      else {
        categoria.removeClass("error");
        return true;
      }
    }
    
    //Perdida de foco
    acronimo.blur(validateAcronimo);
    categoria.blur(validateCategoria);
    
    //Pulsacion de tecla
    acronimo.keyup(validateAcronimo);
    categoria.keyup(validateCategoria);
    // Envio de formulario  
    $("#form1").submit(function() {
      if (validateAcronimo() & validateCategoria()) {
        alert("Guardado");
        return true;
      } else {
        alert("No guardado");
        return false;
      }
    });
    .error {
      background-color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="form1" action="" method="POST" style="margin-bottom:30px;">
      <input type="hidden" name="id" value="" />
    
      <table style="width:500px;">
        <tr>
          <th style="text-align:left;">Acronimo</th>
          <td><input id="acronimo" class="requisites" type="text" name="acronimo" value="" style="width:100%;" required /></td>
    
          <th style="text-align:left;">Categoria</th>
          <td><input id="categoria" class="requisites" type="text" name="categoria" value="" style="width:100%;" required/></td>
        </tr>
        <tr>
          <td colspan="2"><button type="submit" class="btn btn-success">Guardar</button></td>
          <td colspan="2">
            <form action="index.php">
              <input class="btn btn-primary" type="reset" value="Limpiar" />
            </form>
          </td>
        </tr>
      </table>
    </form>
        
    answered by 09.05.2017 / 09:56
    source
    2

    You have a problem with the scope of the variables. Although you indicate in the comment that acronym and category are global variables, they are not. You define them within a function and therefore they are only available within the scope of the function.

    I have modified your code to initialize the event handlers within the document's ready method and initializing the acronym and category variables within the validation functions:

    //funciones de validación
    
    function validateAcronimo() {
        var acronimo = $('#acronimo');
        //No cumple longitud máxima-minima
        if (acronimo.val().length <= 4) {
            acronimo.addClass("error");
            return false;
        }
        //Si lognitud pero no caracteres
        else if (!acronimo.val().match(/^[A-Z]+$/)) {
            acronimo.addClass("error");
            return false;
        }
        //Si longitud, si caracteres
        acronimo.removeClass("error");
        return true;
    }
    function validateCategoria() {
        var categoria = $('#categoria');
        //Longitud máxima
        if (categoria.val().length <= 50) {
            categoria.addClass("error");
            return false;
        }
        //Si
        categoria.removeClass("error");
        return true;
    }
    
    $(document).ready(function () {
        var acronimo = $("#acronimo");
        var categoria = $("#categoria");
    
        //Perdida de foco
        acronimo.blur(validateAcronimo);
        categoria.blur(validateCategoria);
    
        //Pulsacion de tecla
        acronimo.keyup(validateAcronimo);
        categoria.keyup(validateCategoria);
        
        // Envio de formulario  
        $("#form1").submit(function () {
          return validateAcronimo() && validateCategoria();
        });
    });
    .error{
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="form1" action="actualizar" method="POST" style="margin-bottom:30px;">
                <input  type="hidden" name="id" value="" />
    
                <table style="width:500px;">
                    <tr>
                        <th style="text-align:left;">Acronimo</th>
                        <td><input  id="acronimo" class="requisites" type="text" name="acronimo"  value="" style="width:100%;" required /></td>
    
                        <th style="text-align:left;">Categoria</th>
                        <td><input id="categoria" class="requisites" type="text" name="categoria"  value="" style="width:100%;" required/></td>
                    </tr>
                    <tr>
                        <td colspan="2"><button type="submit" class="btn btn-success">Guardar</button></td>
                        <td colspan="2">
                            <form action="index.php">
                                <input class="btn btn-primary" type="reset" value="Limpiar" />
                            </form></td>
                    </tr>
                </table>
            </form>
        
    answered by 09.05.2017 в 09:58