Jquery Validate自定义错误消息位置

ih99xse1  于 2023-08-04  发布在  jQuery
关注(0)|答案(8)|浏览(167)

这看起来很简单,但我想不通。我正在使用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>

的数据

6yoyoihd

6yoyoihd1#

您应该使用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>

如果你想保留你的结构

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>
xwmevbvl

xwmevbvl2#

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

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

字符串
希望有帮助!

0sgqnhkj

0sgqnhkj3#

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

字符串
试试这个获取错误对象的文本

vuktfyat

vuktfyat4#

超文本标记语言

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

x6h2sr28

x6h2sr285#

例如,只需添加一个与输入字段具有+“-error”相同id的空标签标签。

<input id="myID1" required>
<input id="myID2" required>
<div>
    <label id="myID1-error" class="error" for="myID1"></label>
    <label id="myID2-error" class="error" for="myID2"></label>
</div>

字符串

nwlqm0z1

nwlqm0z16#

这对我很有效
实际上,error是一个数组,其中包含了我们传递的元素的错误信息和其他值,你可以console.log(error);请参阅. Inside if condition“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')));
        }
      }
    });

字符串

cidc1ykv

cidc1ykv7#

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

errorLabelContainer: '#errors'

字符串
在你的html中,在你想捕捉错误的地方简单地写上:

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


所有错误都将保存在div中,与输入框无关。
对我来说效果很好。

628mspwn

628mspwn8#

下面是使用jQuery验证逻辑在不同位置显示错误消息的代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#form').validate({
                errorPlacement: function(error, element) {
                    if (element.attr("name") == "policy_accepted") {
                        error.appendTo($('#policy_accepted_error'))
                    } else {
                        error.insertAfter(element);
                    }
                },
                errorClass: 'text-danger',
                rules: {
                    policy_accepted: {
                        required: true,
                    }
                },
                messages: {
                  policy_accepted: {
                        required: "You have to accept our terms & condition",
                    },
                } 
            });
        });
    </script>

个字符

相关问题