4

We have 2 input textfields on the screen whose combination makes up a valid entry. We are doing remote validation on both of them.

Our ViewModel:

[Remote("IsExampleValid", "Validation", AdditionalFields = "Field2")]
public int Field1 { get; set; }

[Remote("IsExampleValid", "Validation", AdditionalFields = "Field1")]
public int Field2 { get; set; }

The problem is these still fire separately and do not truly act together like we need. For example, if I enter bad data in both of them to make an invalid entry then they both will have an error. If I change Field2 to make a valid combination, the remote validation method will get called and mark Field2 as valid. However, Field1 will still be invalid. Field1 should be valid though because they are a combination. Is there a better way to do 2 fields that make up a valid combination?

4

2 回答 2

4

您可以使用Kiff 提供的这段很棒的代码:

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("[id$="+fieldName+"]").change(function () {
                 if ($element.is(':enabled'))
                 {
                     // force re-validation to occur
                     $element.removeData("previousValue");

                     $element.valid();
                 }
            });
        });
    });
}

调用函数:

$(document).ready(function() {
    initializeRemotelyValidatingElementsWithAdditionalFields($("form"));
});

注意:我调整了该$form.find部分,以便它在使用编辑可变长度列表时工作,ASP.NET MVC 2 样式在这种情况下元素IDs是前缀。我还添加了$element.is(':enabled')检查,以便仅当页面上当前启用了该元素时才会触发验证。

于 2013-07-22T05:43:09.770 回答
1

MVC 远程验证 - 清除或设置其他字段错误

public int Field1 { get; set; }

    [Remote("IsExampleValid", "Validation", AdditionalFields = "Field1")]
    public int Field2 { get; set; }

jquery代码在这里

$('#Field1').on('change', function () {
       //code
        $('#Field2').removeData('previousValue');
    });

远程验证检查是否有效后,它的工作附加字段值更改

于 2017-05-25T07:25:52.467 回答