Jquery-Validate中,如何引用label中的属性名?

In Jquery-Validate, how to refer to the name of an attribute in label?

我想使用标签文本作为验证消息。为了做到这一点,我尝试使用 $(label[for="nameAttrName"]),此处的代码片段:

$("#myForm").validate({
  rules: {
    NameQuery: "required"
  },
  messages: {
    NameQuery: "Please fill in " + $(`label[for="NameQuery"]`).text()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>


<form id="myForm">
  <label for="NameQuery">Name Query </label>
  <input name="NameQuery"/>
  <input type="submit" value="Submit"/>
</form>

问题是,我怎样才能在 for="" 位中引用属性名称,这样我就不必显式地写 for="NameQuery" 了?像这样

Question is, how can I refer to the attribute name in the for="" bit so I don't have to write for="NameQuery" explicitly?

不确定为什么需要笼统地编写此代码,因为无论如何您都必须在 rulesmessages 对象中明确列出每个字段。

但是,您通常可以将相对于正在验证的字段的前一个 label 元素作为目标...

"Please fill in " + $(element).prev('label').text();

并且必须从 function() 中返回,以便从插件中获取 element 参数...

....
required: function(params, element) {
    return "Please fill in " + $(element).prev('label').text();
}
....

演示:

$("#myForm").validate({
  rules: {
    NameQuery: {
       required: true
    }
  },
  messages: {
    NameQuery: {
        required: function(params, element) {
            return "Please fill in " + $(element).prev('label').text();
        }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>


<form id="myForm">
  <label for="NameQuery">Name Query </label>
  <input type="text" name="NameQuery" />
  <input type="submit" value="Submit"/>
</form>