【问题标题】:KendoUI, Knockout, conditional validation of a fieldKendoUI,Knockout,字段的条件验证
【发布时间】:2012-10-11 08:30:31
【问题描述】:

我正在使用带有 knockoutjs 的 kendoui 小部件作为数据源。我有一个复选框,数据绑定到StartClientFromWebEnabled 可观察变量。仅当复选框 ic 被选中(StartClientFromWebEnabled 为真)时,输入文本框才可见。输入具有必需的属性。我希望仅在选中复选框时触发所需的验证。

这是我的html:

<table>
    <tr>
        <td><label for="startClientFromWebEnabled">Client Launch From Web:</label></td>
        <td><input type="checkbox" id="startClientFromWebEnabled" name="startClientFromWebEnabled" data-bind="checked: StartClientFromWebEnabled, enable: IsEditable" onchange="startClientFromWebToggleRequiredAttribute()" /></td>
    </tr>
    <tr data-bind="visible: StartClientFromWebEnabled">
        <td><label for="mimeType">Protocol:</label></td>
        <td>
            <input  id="mimeType" name="mimeType" data-bind= "value: MimeType, enable: IsEditable" />
            <span class="k-invalid-msg" data-for="mimeType"></span>
        </td>
    </tr>
</table>

我尝试了一些场景,包括在复选框上设置onChange event,并使用以下javascript函数添加和删除所需的属性:

startClientFromWebToggleRequiredAttribute = function () {
    var checkbox = document.getElementById("startClientFromWebEnabled");
    var mimeType = document.getElementById("mimeType");
    if (checkbox.checked) {
        mimeType.setAttribute("required", "required");
    }
    else {
        mimeType.removeAttribute("required");
    }
}

问题是我的应用程序中的许多相关属性都需要此功能,我的选择是使用一些参数使此函数成为通用函数,并使用相应的参数值从 html 中调用它,如下所示:

toggleRequiredAttribute = function (checkboxElement, inputElement1, inputElement2 ... ) {
    var checkbox = document.getElementById(checkboxElement);
    var inputElement1 = document.getElementById(inputElement1);
    if (checkbox.checked) {
        inputElement1.setAttribute("required", "required");
    }
    else {
        inputElement1.removeAttribute("required");
    }
}

<input type="checkbox" id="startClientFromWebEnabled" name="startClientFromWebEnabled" data-bind="checked: StartClientFromWebEnabled, enable: IsEditable" onchange="toggleRequiredAttribute('startClientFromWebEnable', 'mimeType')" />

我真的不喜欢这种情况。我想知道 kendoui 中是否有类似条件验证的东西,只有在满足某些条件时才会触发。也欢迎任何其他建议。

【问题讨论】:

    标签: javascript html knockout.js kendo-ui


    【解决方案1】:

    我有同样的问题,我创建了一个自定义验证器,它也处理服务器端验证,这个例子不是 100% 完成,但所有验证都在工作,这验证了取决于复选框状态的字符串长度,它还使用错误消息等资源需要稍作修改,它使用 kendo ui 验证客户端,让我知道这是否有用:

    模型属性:

    public bool ValidateTextField { get; set; }
    
    [CustomValidator("ValidateTextField", 6, ErrorMessageResourceType=typeof(Errors),ErrorMessageResourceName="STRINGLENGTH_ERROR")]
    public string TextField{ get; set; }
    

    自定义验证器:

    [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
    public class CustomValidatorAttribute : ValidationAttribute, IClientValidatable {
    
        private const string defaultErrorMessage="Error here.";
        private string otherProperty;
        private int min;
    
        public CustomValidatorAttribute(string otherProperty, int min) : base(defaultErrorMessage) {
            if(string.IsNullOrEmpty(otherProperty)) {
                throw new ArgumentNullException("otherProperty");
            }
    
            this.otherProperty=otherProperty;
            this.min=min;
            this.ErrorMessage = MyResources.Errors.STRINGLENGTH_ERROR;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
    
            bool valid = true;
            var curProperty = validationContext.ObjectInstance.GetType().
                    GetProperty(otherProperty);
            var curPropertyValue = curProperty.GetValue
    (validationContext.ObjectInstance, null);
            if(Convert.ToBoolean(curPropertyValue)) {
    
                string str=value.ToString();
                valid =  str.Length >= min;
                if(!valid) { return new ValidationResult(MyResources.Errors.STRINGLENGTH_ERROR); }
            }
            return ValidationResult.Success;
        }
    
        #region IClientValidatable Members
    
        public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            var rule=new ModelClientValidationRule {
                ErrorMessage = this.ErrorMessage,
                ValidationType="checkboxdependantvalidator"
            };
    
            rule.ValidationParameters["checkboxid"]=otherProperty;
            rule.ValidationParameters["min"]=min;
    
            yield return rule;
        }
        public override string FormatErrorMessage(string name) {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                name);
        }
    
    
    
    }
    

    Javascript:

    (function ($, kendo) {
        $.extend(true, kendo.ui.validator, {
            rules: { // custom rules
                customtextvalidator: function (input, params) {
                    //check for the rule attribute 
                    if (input.filter("[data-val-checkboxdependantvalidator]").length) {
                        //get serialized params 
                        var checkBox = "#" + input.data("val-checkboxdependantvalidator-checkboxid");
                        var min = input.data("val-checkboxdependantvalidator-min");
                        var val = input.val();
    
                        if ($(checkBox).is(':checked')) {
                            if (val.length < min) {
                                return false;
                            }
                        }        
                    }
                    return true;
                }
            },
            messages: { //custom rules messages
                customtextvalidator: function (input) {
                    // return the message text
                    return input.attr("data-val-checkboxdependantvalidator");
                }
            }
        });
    })(jQuery, kendo);
    

    有用的帖子:

    http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC-3

    http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx

    【讨论】:

    • 我只对客户端验证感兴趣,我对使用 Fluent 验证的服务器端验证没有任何问题。我不太了解您的代码中的 javascript 部分与我的案例有何关联。您能否提供一个包含我发布的示例代码的示例(仅 javascript 部分)。
    • 这可能对您的需求有点过分,但服务器端代码将属性添加到 javascript 使用的复选框和文本框中。当 kendo 验证器触发时,它首先获取文本框的“val-checkboxdependantvalidator-checkboxid”属性,使用它来获取复选框的状态,然后在需要时验证文本框。
    猜你喜欢
    • 2011-10-11
    • 2011-08-27
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多