jQuery Validation on Fields with Complex Names

This took me longer to figure out than it should have, so I thought I'd share it.

Supose we have a multi-step form with dynamically created inputs, following a naming convention, like this..

<input type="text" name="manufacturer[1][model]" value="" />
<input type="text" name="manufacturer[2][model]" value="" />
<input type="text" name="manufacturer[3][model]" value="" />

And we want to validate them all in some way.

Using the jQuery .filter() function we can use regex to match the form inputs using a wildcard in the field name where the index would normally be.

$("#cars input").filter(function(){
		return $(this).attr("name").match(/manufacturer\[(.*)\]\[model\]/);
	})
	.each( function() {
		$(this).rules("add",{
			required: true,
			minlength: 2
		});
	});

Then, using the inbuilt .rules("add", fn) method of the validation plugin we can apply the rules to only the fields that matched our regex.

By Karl Payne

Comments

There are no comments, don't be shy, somebody has to be first.

Leave a comment