Jquery验证自定义错误消息位置

时间:2014-10-22 01:09:34

标签: jquery html jquery-validate

这看起来非常简单,但我无法弄清楚。我正在使用jquery validate插件。我尝试验证<input name=first><input name=second>以将错误消息输出到:

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

我已经开始编写errorPlacement:您可以在其中自定义错误消息位置。

如何将错误消息放在<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>

7 个答案:

答案 0 :(得分:75)

您应该使用的是errorLabelContainer

&#13;
&#13;
jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorElement : 'div',
    errorLabelContainer: '.errorTxt'
  });
});
&#13;
.errorTxt{
  border: 1px solid red;
  min-height: 20px;
}
&#13;
<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>
&#13;
&#13;
&#13;


如果你想保留你的结构,那么

&#13;
&#13;
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);
      }
    }
  });
});
&#13;
#errNm1 {
  border: 1px solid red;
}
#errNm2 {
  border: 1px solid green;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:14)

您可以简单地创建与同一功能中所需字段匹配的额外条件。例如,使用上面的代码......

$(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
});

希望有所帮助!

答案 2 :(得分:1)

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

尝试此获取错误对象的文本

答案 3 :(得分:0)

在您的validate方法中添加以下代码:

 errorLabelContainer: '#errors'

,然后在您的html中,将其简单地放在要捕获错误的位置:

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

所有错误都将保留在div中,与您的输入框无关。

对我来说很好。

答案 4 :(得分:0)

JQUERY表单验证自定义错误消息

Demo & example

$(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="john@doe.com"><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>

答案 5 :(得分:0)

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
    });
});

答案 6 :(得分:0)

这对我有用

实际上error是一个数组,其中包含错误消息和我们传递的元素的其他值,您可以console.log(error);看看。 如果条件为“ error.appendTo($(element).parents('div')。find($('。errorEmail')));“; 就是在代码中找到html元素并传递错误消息。

    $("form[name='contactUs']").validate({
rules: {
    message: 'required',
    name: "required",
    phone_number: {
        required: true,
        minlength: 10,
        maxlength: 10,
        number: false
    },
    email: {
        required: true,
        email: true
    }
},
messages: {
    name: "Please enter your name",
    email: "Please enter a valid email address",
    message: "Please enter your message",
    phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
        $("#errorText").empty();

        if(error[0].htmlFor == 'name')
        {
            error.appendTo($(element).parents('div').find($('.errorName')));
        }
        if(error[0].htmlFor == 'email')
        {
            error.appendTo($(element).parents('div').find($('.errorEmail')));
        }
        if(error[0].htmlFor == 'phone_number')
        {
            error.appendTo($(element).parents('div').find($('.errorMobile')));
        }
        if(error[0].htmlFor == 'message')
        {
            error.appendTo($(element).parents('div').find($('.errorMessage')));
        }
      }
    });