我想确认Ville
+ Code-postal
+ Pays
是唯一的。
如果验证没有通过,我想将字段标记为无效(通常为红色)。
我已经尝试过如下的第一个实现:
public class CityEditViewModel
{
public int CityID { get; set; }
[Required, Remote("CityAlreadyExists", "City", AdditionalFields = "CountryID, CityID, PostCode", ErrorMessageResourceName = "CityAlreadyExists", ErrorMessageResourceType = typeof(UserResource))]
[Display(Name = "City", ResourceType = typeof(UserResource))]
public string CityName { get; set; }
[Required, Remote("CityAlreadyExists", "City", AdditionalFields = "CountryID, CityID, CityName", ErrorMessageResourceName = "CityAlreadyExists", ErrorMessageResourceType = typeof(UserResource))]
[Display(Name = "PostCode", ResourceType = typeof(UserResource))]
public string PostCode { get; set; }
[Required, Remote("CityAlreadyExists", "City", AdditionalFields = "CityName, PostCode, CityID", ErrorMessageResourceName = "CityAlreadyExists", ErrorMessageResourceType = typeof(UserResource))]
[Display(Name = "Country", ResourceType = typeof(UserResource))]
public int CountryID { get; set; }
public List<SelectListItem> Countries { get; set; }
}
但所有字段都没有经过检查(验证),直到我真正改变它的内容。我需要一个解决方案,每当我更改3个字段中的一个时,所有3个字段都会被验证并在需要时标记为红色。
我已经检查了其他Stackoverflow帖子,但没有找到解决我特定问题的方法。
感谢您的帮助。
答案 0 :(得分:2)
我也有类似的情景,这个帮助我开始了
$("#FirstName").change(function () {
$('#CardNumber').removeData('previousValue');
$('#CardNumber').valid();
});
答案 1 :(得分:1)
扩展了Suchan的答案,我写了这个帮助器方法,找到每个具有“附加字段”的远程验证元素,然后每当其中一个字段发生变化时,就会激活所述元素的验证。
// I hate naming things
function initializeRemotelyValidatingElementsWithAdditionalFields($form) {
var remotelyValidatingElements = $form.find("[data-val-remote]");
$.each(remotelyValidatingElements, function (i, element) {
var $element = $(element);
var additionalFields = $element.attr("data-val-remote-additionalfields");
if (additionalFields.length == 0) return;
var rawFieldNames = additionalFields.split(",");
var fieldNames = $.map(rawFieldNames, function (fieldName) { return fieldName.replace("*.", ""); });
$.each(fieldNames, function (i, fieldName) {
$form.find("#" + fieldName).change(function () {
// force re-validation to occur
$element.removeData("previousValue");
$element.valid();
});
});
});
}
像这样调用函数:
$(document).ready(function() {
initializeRemotelyValidatingElementsWithAdditionalFields($("#myFormId"));
});