2

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!

Sparky
  • 98,165
  • 25
  • 199
  • 285
Mike
  • 399
  • 2
  • 9
  • 19

2 Answers2

9

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
3

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);
});
Sakeer
  • 1,885
  • 3
  • 24
  • 43
  • 2
    Can you expand on the explanation here, how does this code allow the validator to find the elements based on the id attribute? – emeraldjava Jan 08 '16 at 17:31
  • OP is asking *"**why** does the name attribute have to be present on the element?"* - So instead of answering the actual question, you programmatically find and copy the `name` attribute into the method. Completely pointless - if you have a `name` then use the `name`. Otherwise you can use the `.rules()` method to assign rules by `id`, even though a unique `name` on each field element is still a mandatory requirement for this plugin. However, OP wants to to know if he can avoid using `name` attributes altogether and that's just impossible with this plugin. – Sparky Aug 01 '19 at 22:21