jquery 使用特定位置验证错误位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16099530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:26:08  来源:igfitidea点击:

jquery validate errorplacement with a specific place

jqueryjquery-validate

提问by casper

i want to validate my form with jquery validate but i want to put my error label to a specific place. an example below show error label put in the <span class="error_label"></span>. my question is how can i make errorplacement with a specific place, with an example below, please help me..thanks?

我想用 jquery validate 验证我的表单,但我想把我的错误标签放到一个特定的地方。下面的示例显示了放在<span class="error_label"></span>. 我的问题是如何在特定位置进行错误放置,下面是一个示例,请帮助我..谢谢?

<script>
$(document).ready(function (){
$("#fm_regis").validate({
    rules :{
        name: {
            required: true,
        },
    },
    errorPlacement: function(error, element) {      
        //$(element).next('span .error_label :first').html(error);
        //$('.error_label').html(error);
        //$('.error_label').html(error);
        $(element).closest('.error_label').html(error);
    },
    messages: {
        name: {
            required: "Please input a username",
        },
    }
});
});
</script>

    <form name="fm_regis" id="fm_regis">
    <table>   
      <tr>
         <td width="100">Nama</td>
         <td>:</td>
         <td><input type="text" name="name" id="name" size="30"/></td>
      </tr> 
      <tr>
         <td width="100"></td>
         <td></td>
         <td><span class="error_label"></span></td>
      </tr>
   </table>
     <input type="submit" value="Register"/>
   </form>

采纳答案by dfsq

In your specific situation you can do something like this:

在您的特定情况下,您可以执行以下操作:

$(element).closest('tr').next().find('.error_label').html(error);

http://jsfiddle.net/kqTQu/

http://jsfiddle.net/kqTQu/

回答by Mathijs Flietstra

Try this:

尝试这个:

$("#fm_regis").validate({
  rules :{
    name: {
      required: true,
    },
  },   
  errorLabelContainer: "#id-of-your-specific-place",
  // More of your code
})

And get rid of the errorPlacement:function.

并摆脱该errorPlacement:功能。

回答by ripu1581

Not sure if I have understood the question correctly, try to change this line

不确定我是否正确理解了问题,请尝试更改此行

$(element).closest('.error_label').html(error);

to

$(element).append( "<span class="error_label">" + error + "</span>") ;

make sure that you remove all error labels before initiating validation

确保在开始验证之前删除所有错误标签