web-dev-qa-db-fra.com

Jquery Valider l'emplacement du message d'erreur personnalisé

Cela a l'air très simple, mais je ne peux pas le comprendre. J'utilise le plugin jquery validate. J'essaie de valider <input name=first> et <input name=second> pour afficher les messages d'erreur dans:

<span id="errNm2"></span> <span id="errNm1"></span>

J'ai déjà commencé à écrire errorPlacement: c'est là que vous personnalisez l'emplacement de votre message d'erreur.

Comment puis-je mettre le message d'erreur dans ces <span>?

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            error.append($('.errorTxt span'));
        },
        rules,
});
<input type="text" name="first"/>
<input type="text" name="second"/>

<div class="errorTxt">
   <span id="errNm2"></span>
   <span id="errNm1"></span>
</div>
31
learntosucceed

Ce que vous devez utiliser est le errorLabelContainer

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorElement : 'div',
    errorLabelContainer: '.errorTxt'
  });
});
.errorTxt{
  border: 1px solid red;
  min-height: 20px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" />
  <input type="text" name="second" />
  <div class="errorTxt"></div>
  <input type="submit" class="button" value="Submit" />
</form>

Si vous voulez conserver votre structure alors

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorPlacement: function(error, element) {
      var placement = $(element).data('error');
      if (placement) {
        $(placement).append(error)
      } else {
        error.insertAfter(element);
      }
    }
  });
});
#errNm1 {
  border: 1px solid red;
}
#errNm2 {
  border: 1px solid green;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" data-error="#errNm1" />
  <input type="text" name="second" data-error="#errNm2" />
  <div class="errorTxt">
    <span id="errNm2"></span>
    <span id="errNm1"></span>
  </div>
  <input type="submit" class="button" value="Submit" />
</form>
77
Arun P Johny

Vous pouvez simplement créer des conditions supplémentaires qui correspondent aux champs requis dans la même fonction. Par exemple, en utilisant votre code ci-dessus ...

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            //Custom position: first name
            if (element.attr("name") == "first" ) {
                $("#errNm1").text(error);
            }
            //Custom position: second name
            else if (element.attr("name") == "second" ) {
                $("#errNm2").text(error);
            }
            // Default position: if no match is met (other fields)
            else {
                 error.append($('.errorTxt span'));
            }
        },
        rules
});

J'espère que ça t'as aidé!

14
Pete
 if (e.attr("name") == "firstName" ) {
     $("#firstName__validate").text($(error).text());
     console.log($(error).html());
 }

Essayez ceci avec get text of error object

1
Pankaj Mandale

Ajoutez ce code dans votre méthode validate:

 errorLabelContainer: '#errors'

et dans votre html, mettez simplement ceci où vous voulez attraper l'erreur:

<div id="errors"></div>

Toutes les erreurs se dérouleront dans la division, indépendamment de votre zone de saisie.

Cela a très bien fonctionné pour moi.

0
Giorgio C.

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});
0
Adel Mourad

MESSAGE D'ERREUR PERSONNALISÉ JQUERY FORM VALIDATION

Démo & exemple

$(document).ready(function(){
  $("#registration").validate({
    // Specify validation rules
    rules: {
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        email: true
      },      
      phone: {
        required: true,
        digits: true,
        minlength: 10,
        maxlength: 10,
      },
      password: {
        required: true,
        minlength: 5,
      }
    },
    messages: {
      firstname: {
      required: "Please enter first name",
     },      
     lastname: {
      required: "Please enter last name",
     },     
     phone: {
      required: "Please enter phone number",
      digits: "Please enter valid phone number",
      minlength: "Phone number field accept only 10 digits",
      maxlength: "Phone number field accept only 10 digits",
     },     
     email: {
      required: "Please enter email address",
      email: "Please enter a valid email address.",
     },
    },
  
  });
});
<!DOCTYPE html>
<html>
<head>
<title>jQuery Form Validation Using validator()</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<style>
  .error{
    color: red;
  }
  label,
  input,
  button {
    border: 0;
    margin-bottom: 3px;
    display: block;
    width: 100%;
  }
 .common_box_body {
    padding: 15px;
    border: 12px solid #28BAA2;
    border-color: #28BAA2;
    border-radius: 15px;
    margin-top: 10px;
    background: #d4edda;
}
</style>
</head>
<body>
<div class="common_box_body test">
  <h2>Registration</h2>
  <form action="#" name="registration" id="registration">
 
    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>
 
    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>
 
    <label for="phone">Phone</label>
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  
 
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>
 
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder=""><br>
 
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">
  </form>
</div>
 
</body>
</html>
0
Developer