4

我想验证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 帖子,但没有找到解决我的具体问题的方法。

谢谢你的帮助。

4

2 回答 2

2

我也有类似的情况,这个帮助我开始了

$("#FirstName").change(function () {
        $('#CardNumber').removeData('previousValue');
        $('#CardNumber').valid();
  });

使用远程验证进行多字段验证

于 2012-11-12T21:54:56.153 回答
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"));
});
于 2013-07-19T13:49:41.003 回答