I’ve created a jQuery function for unobtrusive MVC 3 validation…
$.validator.addMethod('dtdt',
function (value, element, parameters) {
var idmonth = '#' + parameters['m'];
var idyear = '#' + parameters['y'];
var idhour = '#' + parameters['h'];
var idminute = '#' + parameters['mn'];
var controlmonth = $(idmonth);
var controlyear = $(idyear);
var controlhour = $(idhour);
var controlminute = $(idminute);
var mv = controlmonth.val();
var yv = controlyear.val();
var hv = controlhour.val();
var mnv = controlminute.val();
if (value == "" || mv == "" || yv == "" || hv == "" || mnv == "")
if (value != "" || mv != "" || yv != "" || hv != "" || mnv != "")
return $.validator.methods.required.call(
this, value, element, parameters);
return true;
}
);
The idea behind this is that I have 5 dropdown controls next to each other (Day, Month, Year, Hour and Minute). I’ve put this validator on the Day dropdown.
The rule is:- If one is empty then they must all be empty. I one if filled in, then they must all be filled in.
The Day dropdown value is passed into the function using “value”. The other values are retrieved directly from the controls. This bit is working fine.
When I debug, the code correctly seems to call the “return $.validator” statement exactly when I expect it. However the form still seems to submit to server side. The only exception is if it’s the Day dropdown I’ve left blank. If I’ve instead left the Month dropdown blank the validator is not working.
Is what I want to do achievable? It seems like overkill to put this validator on each of the 5 controls.
The problem is the fact that you have put this validator on the Day dropdown. To make it work, it should call $.validator.methods.required.call for the proper empty element, something like this:
This code is still not perfect but it should give you an idea in which direction you should go.