继上面 Chris 的辅助方法之后。这在大多数情况下都很好用,但如果您的模型完全有前缀,例如 'Custom.Address.Line1' 。未正确找到附加字段。我已经使用 jquery.validate.unobstructive 库中的一些附加逻辑更新了帮助程序,这些逻辑将正确查找字段。
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function initializeRemotelyValidatingElementsWithAdditionalFields($form) {
const remotelyValidatingElements = $form.find("[data-val-remote]");
$.each(remotelyValidatingElements, function (i, element) {
var $element = $(element);
const additionalFields = $element.attr("data-val-remote-additionalfields");
if (additionalFields.length === 0) return;
const rawFieldNames = additionalFields.split(",");
const prefix = getModelPrefix(element.name);
const fieldNames = $.map(rawFieldNames, function(fieldName) {
return appendModelPrefix(fieldName, prefix);
});
$.each(fieldNames, function (i, fieldName) {
$form.find(":input").filter("[name='" + escapeAttributeValue(fieldName) + "']").change(function () {
// force re-validation to occur
$element.removeData("previousValue");
$element.valid();
});
});
});
}