-1

I'm practising html with bootstrap 4 and jQuery validate, I need to know how I can use errorPlacement for a specific element or several elements? The error messages are appearing in the inputs, however, I want them to appear below them in a small

I update all my code, so you can see it from a PC, import the necessary links, I also have it here : https://codepen.io/CoudVan/project/editor/ZQyGjK:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Material Design Bootstrap</title>
    <!-- Bootstrap css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <!-- Material Design Bootstrap -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.0/css/mdb.min.css" rel="stylesheet">
    <!-- Css Personalizado -->
    <style>
    *{
  padding: 0;
  margin: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.user{
  font-size: 1.8rem;
  margin-right: 2%;
}
  body{
    background-color: rgba(236, 239, 243, 0.3); }
form div small{
  color: red;
}


.miclase{
  color: red;
}
  </style>



</head>

<body>

  <header>
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top primary-color">

    <!-- Navbar brand -->
    <a class="navbar-brand" href="#">Logo Chat</a>

    <!-- Collapse button -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#NavbarPrincipal" aria-controls="NavbarPrincipal" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="NavbarPrincipal">

        <!-- Links -->
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Inicio
                  <span class="sr-only">Navbar de Pagina</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Menu</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Acerca de</a>
            </li>
        </ul>
        <!-- Links -->

        <form class="form-inline">
            <div class="md-form my-0">
              <input class="form-control mr-sm-2" type="search" placeholder="Buscar" aria-label="Search">
            </div>
            <button class="btn btn-outline-white btn-md my-2 my-sm-0 ml-3" type="submit">Buscar</button>
        </form>
      </div>
      <!-- Collapsible content -->
      </nav>

  </header>
    <section>
        <div class="container my-5">
            <div class="row align-items-center">
              <div class="col-md-7 my-4">
                <div class="col-md-11 mb-5 mt-md-0 mt-5 text-center text-md-left animated fadeInLeft" data-wow-delay="0.3s">
                  <h1 class="display-4 font-weight-bold">Lorem ipsum</h1>
                  <hr class="hr-dark">
                  <h6 class="mb-3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem repellendus quasi fuga nesciunt dolorum nulla magnam veniam sapiente, fugiat! Commodi sequi non animi ea dolor molestiae, quisquam iste.</h6>
                  <a class="btn btn-outline-blue">Learn more</a>
                </div>  
              </div>
              <div class="col-md-5">
                  <div class="card animated fadeInRight my-4 bg-transparent" data-wow-delay="0.3s">
                      <div class="card-body">
                        <form action="" id="formulario" name="formulario">
                            <div class="row py-4 d-flex justify-content-center">
                            <i class="user fas fa-user"></i>
                            <h3 class="">Registrate</h3>
                            </div>
                            <div class="form-row">
                              <div class="form-group col md-form">
                                <input type="text" class="form-control" id="nombres" name="nombres">
                                <label for="nombres" id="nom" class="font-weight-light mx-1">Nombres</label>
                              </div>
                              <div class="form-group col md-form">
                                <input type="text" class="form-control" id="apellidos" name="apellidos" >
                                <label for="apellidos" class="font-weight-light mx-1">Apellidos</label>

                              </div>
                            </div>
                            <div class="form-group md-form">
                              <input type="text" name="usuario" class="form-control" id="usuario"> 
                              <label for="usuario" class="font-weight-light">Usuario</label> 
                            </div>
                            <div class="form-group md-form">
                              <input type="email" class="form-control" name="email" id="email">
                              <label for="email" class="font-weight-light">Correo Electrónico</label>
                            </div>
                            <div class="form-row">
                              <div class="form-group col md-form">
                                <input type="password" class="form-control" id="clave" name="clave">
                                <label for="clave" class="font-weight-light mx-1">Contraseña</label>
                              </div>
                              <div class="form-group col md-form">
                                <input type="password" class="form-control" id="clavecon" name="clavecon">
                                <label for="clavecon" class="font-weight-light mx-1">Confirmar Contraseña</label>
                              </div>
                            </div>
                            <div class="form-check col-12">
                                <input type="checkbox" class="form-check-input" id="terminos" name="terminos">
                                <label for="terminos" class="form-check-label grey-text">Acepta los <a href="#" class="font-weight-light">Términos y Condiciones</a></label>
                            </div>
                            <div class="text-center md-form">
                              <input type="submit" class="btn btn-primary btn-rounded" value="Registrate">
                            </div>
                       </form>
                     </div>
                  </div>
              </div>
            </div>
          </div>
    </section>

    <!-- SCRIPTS -->
     <!-- Fonts Awesome -->
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/all.js" integrity="sha384-xymdQtn1n3lH2wcu0qhcdaOpQwyoarkgLVxC/wZ5q7h9gHtxICrpcaSUfygqZGOe" crossorigin="anonymous"></script>
    <!-- JQuery -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script
    <!-- JQuery Validate -->
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
    <!-- Bootstrap tooltips -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <!-- Bootstrap core JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <!-- MDB core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.0/js/mdb.min.js"></script>
    <script>
      new WOW().init();
    </script>
    <script>
      $(document).ready(function(){
        $("#formulario").validate({
          rules:{
            nombres:{
              required:true,
              maxlength:50
            },
            apellidos:{
              required:true,
              maxlength:50
            },
            usuario:{
              required:true,
              maxlength:30
            },
            email:{
              required:true,
              email:true,
              maxlength:120
            },
            clave:{
              required:true,
              minlength:8,
              maxlength:20
            },
            clavecon:{
              required:true,
              equalTo : "#clave"
            },
            terminos:{
              required:true,
            }
          },
          messages:{
            nombres:{
              required:'Ingresa tu Nombre',
              maxlength:'Por favor, no ingreses más de 50 carácteres'
            }
            ,
            apellidos:{
              required:'Ingresa tu Apellido',
              maxlength:'Por favor, no ingreses más de 50 carácteres'
            },
            usuario:{
              required:'Ingresa un nombre de Usuario',
              maxlength:'Por favor, no ingreses más de 30 carácteres'
            },
            email:{
              required:'Ingresa tu Correo Electrónico',
              email:'Ingresa el formato correcto @',
              maxlength:'Por favor, no ingreses más de 120 carácteres'
            },
            clave:{
              required:'Ingresa una contraseña',
              minlength:'Usa de 8 a 20 carácteres para tu contraseña',
              maxlength:'Usa de 8 a 20 carácteres para tu contraseña'
            },
            clavecon:{
              required:'Confirma tu contraseña',
              equalTo : "#clave"
            },
            terminos:{
              required:'Marca la casilla',
            }
          },
          errorPlacement: function(error, element) {
             (this is my dude, error the error messages appear in the inputs, and I want them below with a small)
          }
        });
      });
    </script>
</body>

</html>
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • I created a snippet. Please update with the validation rules you have to make a [mcve] – mplungjan May 22 '18 at 08:19
  • See updated answer. – 4b0 May 22 '18 at 09:31
  • https://stackoverflow.com/questions/46542980/bootstrap-4-beta-jquery-validation?s=1|43.2210 – Sparky May 22 '18 at 15:17
  • Please use the search function before posting. You've also made no attempt whatsoever at writing a custom `errorPlacement` function. You should at least show us what you've tried before asking us to write it all for you. – Sparky May 22 '18 at 15:21
  • Hello, use the search function and the solutions I found did not solve my problem. Quite apart, the solutions that were published, served but not completely, because in the checkbox, the error message appears almost outside the card. – Pedro P Segura May 23 '18 at 14:35
  • I solved the problem adding **div** after the following input : [div] [input = checkbox name = terms] [label] [a] [/ a] [/ label] [div] ** [div] [/ div] ** and adding in the js, the following: errorElement: "small",        errorPlacement: function (error, element) {          if (element.attr ("name") == "terms") {            error.appendTo (element.parent ("div"). next ("div"));          } else {            error.insertAfter (element);          }        } – Pedro P Segura May 23 '18 at 14:43

2 Answers2

0

Use errorPlacement with custom css like this.

 $('#myform').validate({
   errorPlacement: function(label, element) {
     label.addClass('custom');
     label.insertAfter(element);
   },
   wrapper: 'span'
 });

and write css for your desire style using custom.

Snippet with custom class.

$('#myform').validate({
  errorPlacement: function(label, element) {
    label.addClass('custom');
    label.insertAfter(element);
  },
  wrapper: 'span'
});
.custom {
  position: absolute;
  top: 30px;
  left: 0;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src='https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js'></script>
<form action='' method='post' id='myform'>
  <input type='text' name='username' required />
  <input type='submit' value='submit' />
</form>

Snippet without custom class.

$('#myform').validate({
  errorPlacement: function(label, element) {
    label.addClass('custom');
    label.insertAfter(element);
  },
  wrapper: 'span'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src='https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js'></script>
<form action='' method='post' id='myform'>
  <input type='text' name='username' required />
  <input type='submit' value='submit' />
</form>
4b0
  • 21,981
  • 30
  • 95
  • 142
  • You would not use `errorPlacement` for adding CSS classes. Dynamically adding/removing classes are what the `highlight` and `unhighlight` callbacks were designed to handle. There is also no point in dynamically adding a class to the error message when the visibility of this entire element is just going to be toggled by the plugin. Since your `custom` CSS class is not toggling, you could more easily just target the error message element with pure CSS.... `label.error` would do it. – Sparky May 22 '18 at 19:16
-1

You can append the label element and add the error message on validation.

$('label#your_id').append('<small> This field is required. </small>');
Tajuddin
  • 73
  • 3
  • 13