Dave
Dave

Reputation: 2562

Using JQuery unobtrusive validation to highlight a different field from what is being validated

We have an MVC 4 project set up with JQuery unobtrusive validation and some custom validators. One of these is a date range validator, where 2 textfields get passed to one object on the viewmodel (as 'PropertyName'.Min and 'PropertyName'.Max).

I've had no problem validating the fields and getting the validator method to validate based on these text fields (I use a dummy hidden field called 'PropertyName'). However as the validation is tied to the field "'PropertyName'", 'PropertyName'.Min and 'PropertyName'.Max don't get highlighted.

I've tried bodging the classes in the validator method

$(dateRangeMin).removeClass("input-validation-error");
$(dateRangeMin).removeClass("valid");
$(dateRangeMax).removeClass("input-validation-error");
$(dateRangeMax).removeClass("valid");

Then assigning those classes based on the validation, but it doesn't seem to work consistently.

Before I bodge it anymore, does anyone know of any built in way to pass the validation result to a different form field?

UPDATE: The bodge doesn't work because the min and max date fields get validated independently and pass validation. So I'm looking for a way to associate the validation with these fields as well.

Thanks

Dave

Upvotes: 2

Views: 2851

Answers (1)

chrismilleruk
chrismilleruk

Reputation: 2516

It sounds to me like the core of this issue is that you have multiple inputs that represent one item on your model.

If that is the case, there are two ways to go from there:

  1. Switch to a View Model approach where each user input is represented by a unique property on the model.

  2. Have a look at the jQuery validation groups. e.g.

http://docs.jquery.com/Plugins/Validation/validate#toptions

JQuery Validate multiple fields with one error

Upvotes: 1

Related Questions