Multiple fields validation using Remote Validation

前端 未结 4 1174
礼貌的吻别
礼貌的吻别 2020-11-29 03:26

I have the following model:

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

    public string LastName {get; set;}

    [Remote(\"CardExistin         


        
4条回答
  •  清歌不尽
    2020-11-29 04:27

    Following on from Chris's helper method above. This works great in most instances, but if your model has a prefix at all e.g. 'Custom.Address.Line1' . The additional fields are not found correctly. I have updated the helper with some additional logic from the jquery.validate.unobstructive lib which will lookup the fields correctly.

    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($form) {
        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();
                });
            });
        });
    }
    

提交回复
热议问题