Jquery验证错误消息的放置位置?

时间:2018-05-22 08:03:12

标签: jquery twitter-bootstrap jquery-validate

我用bootstrap 4和jQuery验证练习html, 我需要知道如何将errorPlacement用于特定元素或多个元素?错误消息出现在输入中,但是,我希望它们以小的

显示在它们下面

我更新了所有代码,因此您可以从PC上看到它,导入必要的链接,我也在这里: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>

2 个答案:

答案 0 :(得分:0)

errorPlacement与此类自定义css一起使用。

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

并使用css为您的愿望样式写custom

自定义类的片段。

$('#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>

没有自定义类的代码段。

$('#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>

答案 1 :(得分:-1)

您可以附加label元素并在验证时添加错误消息。

$('label#your_id').append('<small> This field is required. </small>');