Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c# - Multiple fields validation using Remote Validation

I have the following model:

public class Customer
{
    public string FirstName {get;set;}

    public string LastName {get; set;}

    [Remote("CardExisting", "Validation", AdditionalFields="FirstName,LastName")
    public string CardNumber {get; set;}
}

CardExisting action will check that there is an existing record for the combination of cardNumber for the firstName and LastName.

What if user will first enter the card number and then his name, I cant validate him, so when he returns and input his name I need to remote validate again, how can I do that when focus was already lost from cardnumber property?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Expanding on Jaluka's answer, I wrote this helper method that finds each remotely validating element that has "additional fields," and then causes validation on said element to fire each time one of those fields changes.

// 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();
            });
        });
    });
}

Call the function like so:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...