Created
October 16, 2018 10:05
-
-
Save johnw86/762a4163b35601b3f68675be8db8caa2 to your computer and use it in GitHub Desktop.
MVC Remote Validation Additionalfields Trigger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(formId) { | |
const $form = $('#' + formId); | |
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(); | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment