How can I replace the JavaScript alert message by text with the error using jquery [duplicated]

2

I need to replace the alert by inserting the error text, and not display that text and / or delete it when there is no error in the data entered. [

$(document).ready(function() {
    $("button").on("click", function() {
        
        //Variables para evaluar el ingreso de datos
        var username = ($('#username').val());
        var password = ($('#password').val());
        var condiciones = $("#terms").is(":checked");
      
        //Validar si se ingresaron los datos
        if (!username) {
           $('#username').parent().addClass('has-error');
            alert("Debe de ingresar un usuario");
             return false;
        } else 
           $('#username').parent().removeClass('has-error');
      
        if (!password) {
           $('#password').parent().addClass('has-error');
            alert("Debe de ingresar una clave");
             return false;
        } else
           $('#password').parent().removeClass('has-error');
        
        if ((password).length < 6) {
           $('#password').parent().addClass('has-error');
            alert("Debe de ingresar una clave mayor a 5 caracteres");
             return false;
        } else
           $('#password').parent().removeClass('has-error');
        
        if ((password).length > 40) {
           $('#password').parent().addClass('has-error');
            alert("Debe de ingresar una clave menor a 40 caracteres");
             return false;
        } else
           $('#password').parent().removeClass('has-error');
      
        if (!condiciones) {
           $('.checkbox').addClass('has-error');
            alert("Debe aceptar las condiciones");
            return false;
        } else
           $('.checkbox').removeClass('has-error');
    });
});
.action {
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Formulario de Registro</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div class="col-sm-6 col-sm-offset-3">
      <h1>Formulario de Registro</h1>
      <form>
        <div class="form-group">
          <label class="control-label" for="username">Usuario:</label>
          <input type="text" class="form-control input-lg" id="username" placeholder="Ingresa un usuario">
          <p class="help-block"></p>
        </div>
        <div class="form-group">
          <label class="control-label" for="password">Contraseña</label>
          <input type="password" class="form-control input-lg" id="password" placeholder="Ingresa una contraseña">
          <p class="help-block"></p>
        </div>
        <div class="checkbox terms-checkbox">
          <label>
            <input type="checkbox" id="terms"> Acepto los términos y condiciones
          </label>
        </div>
        <div class="action text-right">
          <button type="submit" class="btn btn-primary btn-block btn-lg">Registrarse</button>
        </div>
      </form>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>

2 ] 2

    
asked by García Henry 13.05.2018 в 18:04
source

1 answer

1

To achieve what you want there are several ways, what I would do is initialize the variables of the nodes and go review one by one if you have an error.

To have a code more DRY and not have to write several times the same I create a template for the error helper , and I'll deploy it with your text as necessary.

And finally we check the errors you want, if there is no error we send the form.

Your adapted code:

$("button").on("click", function(event) {
  // No enviamos la form a menos que no exista error
  event.preventDefault();
  
  //Nodos de jQuery
  var $username = $('#username');
  var $password = $('#password');
  var $checkbox = $('.checkbox');
  var $helpBlock = $('.help-block');
  var $parent;

  // Removemos las clases de errores
  $username.parent().removeClass('has-error');
  $password.parent().removeClass('has-error');
  $checkbox.removeClass('has-error');
  $helpBlock.remove();

  // Valores de los inputs
  var username = $username.val();
  var password = $password.val();
  var condiciones = $("#terms").is(":checked");
  var helpBlock = '<span class="help-block">%s</span>';
  var hasError = false;
  var textError = '';

  //Validar si se ingresaron los datos
  if (username === '') {
    hasError = true;
    $parent = $username.parent();
    textError = "Debe de ingresar un usuario";
    $parent.addClass('has-error');
    $parent.append(helpBlock.replace('%s', textError));
  }

  if (password === '') {
    hasError = true;
    $parent = $password.parent();
    textError = "Debe de ingresar una clave"
    $parent.addClass('has-error');
    $parent.append(helpBlock.replace('%s', textError));
  }

  if ((password).length < 6) {
    hasError = true;
    $parent = $password.parent();
    textError = "Debe de ingresar una clave mayor a 5 caracteres"
    $parent.addClass('has-error');
    $parent.append(helpBlock.replace('%s', textError));
  }

  if ((password).length > 40) {
    hasError = true;
    $parent = $password.parent();
    textError = "Debe de ingresar una clave mayor a 5 caracteres";
    $parent.addClass('has-error');
    $parent.append(helpBlock.replace('%s', textError));
    $password.parent().addClass('has-error');
  }

  if (!condiciones) {
    hasError = true;
    textError = "Debe aceptar las condiciones";
    $checkbox.addClass('has-error');
    $checkbox.append(helpBlock.replace('%s', textError));
  }

  if (!hasError) {
    $('form').submit();
  }
});
.action {
  margin-top: 30px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">
  <div class="col-sm-6 col-sm-offset-3">
    <h1>Formulario de Registro</h1>
    <form>
      <div class="form-group">
        <label class="control-label" for="username">Usuario:</label>
        <input type="text" class="form-control input-lg" id="username" placeholder="Ingresa un usuario">
      </div>
      <div class="form-group">
        <label class="control-label" for="password">Contraseña</label>
        <input type="password" class="form-control input-lg" id="password" placeholder="Ingresa una contraseña">
      </div>
      <div class="checkbox terms-checkbox">
        <label>
            <input type="checkbox" id="terms"> Acepto los términos y condiciones
          </label>
      </div>
      <div class="action text-right">
        <button type="submit" class="btn btn-primary btn-block btn-lg">Registrarse</button>
      </div>
    </form>
  </div>
</div>
    
answered by 13.05.2018 / 19:36
source