I have an ASP.Net MVC Project and I am using unobtrusive jQuery Validation. to add validation when an element loses focus, I am calling
$(document).ready(function
This can happen also you you didn't call validate() on your form as such:
$("#your_form").validate();
In my case, I had no form with the id "your_form" on my page hence causing this error when trying to add rules.
Looks like your projects use different types of validadion (One of them use unobtrusive and second use default).
Please check if you are using next settings in web.config's of both projects.:
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
Also you are trying to work with first form in your document.
In case when there is no forms - you will get error.
In case when there are more then one form - only first form will use focusout for validation.
So you should do same thing for each form:
$(document).ready(function () {
var $forms = $('form');
$.each($forms, function (key, value) {
// enable validation when an input loses focus.
var settings = $.data(value, 'validator').settings;
settings.onfocusout = function (element) { $(element).valid(); };
});
});
Checkout number of forms first, I think you are using incorrect form.
$(document).ready(function () {
// enable validation when an input loses focus.
if($('form').length > 0) {
// $('form')[0] is it proper form?
var settngs = $.data($('form')[0], 'validator').settings;
settngs.onfocusout = function (element) { $(element).valid(); };
}
});
I just upgraded to Microsoft.jQuery.Unobtrusive.Validation.3.2.0 package. I came across the same problem. Is it possible that you also upgraded to the same version?
If so, I might offer my two cents :). After a bit of debugging I noticed that the following change was made in jquery.validate.unobtrusive.js:
Previous version:
var $forms = $(selector)
.parents("form")
.andSelf()
.add($(selector).find("form"))
.filter("form");
New version:
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]"); // key point!
The key seems to be: the has("[data-val=true]")
. That is, if your form doesn't have any descendents (like an input element) with that attribute value, it will not be parsed by the validation helper and no 'validator' data will get assigned to that form element. You'll then get this 'undefined' error if you try to access the validator of that form at a later stage.
In my case, the forms for which this was happening didn't actually use any validation, hence they didn't have this attribute. I was then able to change my custom validator logic to first check if the validator exists before changing validator settings.
Hope that helps.
Doing this $.validator.unobtrusive.parse($("#base-modal form"));
resolved my issue