I have the following code:
HTML:
<form id="myTestFrom">
<input type="text" name="test_txb" id="test_txb" value="" class="form-control" />
</form>
JS:
$(function () {
$.validator.addMethod('testValidationMethod', function (value, element) {
alert('FIRED');
}, 'test error message');
$('#myTestFrom').validate({
rules: {
/* (*) */
test_txb: { testValidationMethod: true }
}
});
});
The problem is simple: my custom validator method never gets called.
I have read several similar questions and answers here on StackOverflow (for example this), but none of them seemed to work. In fact, right the opposite. Most of them suggested that the jQuery validator works by looking for input fields with the specified name, not the specified id. That is, the object property name at (*) must match the name attribute of the input to be validated. However, as you can see in my code, I do have the test_txb name (as well as id) on my input, but for some reason, my validator method never gets called using the code above.
However, if I add the name of the validator method (testValidationMethod) as a class to my input field, then it does get called. This sounds contradictionary to whatever I have read here on SO since all those answers stated that the default behaviour is that the validator inspects the name attributes of elements when setting up custom validation rules.
So what is going on here, could someone please explain? The simplest solution would certainly be to just add the aforementioned class name but I hate littering my code with otherwise unnecessary stuff especially if I don't fully understand the reason of why I should do that.
Edit: jQuery validator version is 1.15.1
Edit 2: I also have ASP.NET MVC Unobtrusive lib referenced, maybe that conflits with something?
.validate()more than once. Since unobtrusive automatically constructs and calls.validate(), your instance is totally ignored.