JQuery-Validation - using rules method on selected ID, why does the name attribute have to be present on the element?

谁说我不能喝 提交于 2019-11-30 09:07:18

问题


I'm a little confused about the JQuery validation plugin behavior.

If I have the following JQuery:

$('#form1').validate({
    /* other validation */
});

$('#txt1').rules("add",
{
    required: true,
    messages: { required: 'This is required!' }
});

and the following text input, with an id but no name attribute:

<input type="text" id="txt1"/>

No required message pops up on the text box.

However, if I add a name attribute:

<input type="text" id="txt1" name="anything"/>

It validates it just fine.

Why is that? Since I'm using the rules("add", rules) method on an ID selector, why does it need the name attribute present in order to associate rules to the element? Thanks for any insight!


回答1:


A name attribute is required on the element firstly because that's what jQuery validate uses internally as a key for each field, and secondly because the name attribute is required on input elements to ensure the page validates to the specified DOCTYPE.




回答2:


If you want to apply the rules using the id then use like this,

$(function () {
  var $field = $("#id_field").attr("name");
  var $params = {debug:false, rules:{}, messages:{}};
  $params['rules'][$field] = {"required": true, "rule": ["params"]};
  $params['messages'][$field] = "error message";

  $("#frm").validate($params);
});


来源:https://stackoverflow.com/questions/14145283/jquery-validation-using-rules-method-on-selected-id-why-does-the-name-attribu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!