Is there any way to trigger a specific jquery-unobtrusive rule on one field, when the value in another field changes?
I have a form with two date fields (say start/end) on it, with validation that end
must be greater than start
. This works fine in the simple case of changing end
after start
is already set. What it doesn't do is allow for is:
- setting
end
first and then settingstart
- changing
start
after both have already been set, and violating the constraint
Server side validation will catch it of course, but it looks bad to have the error on end
stay set even after you have fixed start
, or no error showing up when the value in end
is changed to an invalid value. The reason to trigger a specific rule is that I don't want to fire off the required
or date
format rules on the same field before the user has had a chance to enter a value. The form starts off 'clean'. However, if that isn't possible then firing all the rules is ok.
Sorry for no code samples, but I don't even know where to start with this.
Update:
What i've done for the moment is to dig around in the model (since this is an asp.net mvc project), find the attribute, and read it's properties directly.
var controllerCtx = ViewContext.Controller.ControllerContext;
var da = ViewData.ModelMetadata.GetValidators(controllerCtx)
.SelectMany(x => x.GetClientValidationRules())
.Where(x => x.ValidationType == "isdateafter")
.FirstOrDefault();
var otherid = da == null ? "" : da.ValidationParameters["propertytested"];
Then in the normal HTML part, I do a test on the start
and see if it is a date picker, then wire up a basic check, and fire off all validation rules. Since there aren't many rules, I just check to see if there is a value in the end
field before running them. I'd like to use the ingenious solution below, and will give it a go when I have a bit of free time this week.
@if (otherid != "") {
<text>
var other = $("#@otherid");
if (other && other.hasClass('hasDatepicker')) { // if the other box is a date/time picker
other.datetimepicker('option', 'onSelect', function(dateText, instance) {
var lowerTime = $(this).datetimepicker('getDate');
$("#@id").datetimepicker('option', 'minDate', new Date(lowerTime.getTime()));
if ($("#@id").val()) { // if there is a value in the other
$('form').data('validator').element('#@id');
}
});
}
</text>
}