JQuery Validator plus Element IDs, and Names

Category:UncategorizedTag: :

OK, just discovered an interesting implementation detail of JQuery Validator (one that I should have known about already as well).

OK, if you have a form where the inputs of the for have both id and name  attributes, the name attributes trump id.

So if you have this:

   1: <input type='type' id='RegisterUserName' name='userName' />

Then you write the validation against ‘user’Name’, not ‘RegisterUserName’.

   1: $("RegisterForm").validate({

   2:     rules: { userName: {required: true} }

   3: });

If you do not you will get all sorts of strange null exception errors (which in JavaScript means something returned as ‘undefined’.

How this happens

People have been talking about the great flexibility of Asp.Net MVC for a while now, but there are a few things to be aware of.  One of them is multiple forms. 

Say you have a web page that has two forms on it, one to register users, the other to log users in.   Both forms have ‘username’ and ‘password’ fields.   Asp.Net MVC still cannot get you around the need to keep ids unique – but names can be reused.   These names are also read by Asp.Net Action Controllers.  So if you have multiple forms all submitting to the same Controller Action, as long as the name attributes are set it will hook up.

Anyway, this is a short post, mostly for myself, so I don’t spend two hours figuring this out again.

4 thoughts on “JQuery Validator plus Element IDs, and Names

  1. To reinforce your point, the key distinction is that form elements have an ID that represents them client-side, and each of those elements has two attributes sent to the server in a form submission: name & value. Unless you need to manipulate them client-side, you don’t need IDs on your form elements (I think the MVC TextBox helper renders an ID automatically, which it really shouldn’t do since they’re not required).

  2. I am with Richard on this one, as I typically have to assign labels to my inputs.

    Side note: NEVER give your submit button an ID of ‘submit’. You just don’t want to go there.

Comments are closed.

Find me

RSS
Facebook
Twitter
LinkedIn

Disclaimer

The opinions and content expressed here are my own and not those of my employer.