0

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

这是我的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 中是否有类似条件验证的东西,只有在满足某些条件时才会触发。也欢迎任何其他建议。

4

1 回答 1

0

我有同样的问题,我创建了一个自定义验证器,它也处理服务器端验证,这个例子不是 100% 完成,但所有验证都在工作,这验证了取决于复选框状态的字符串长度,它还使用资源来处理错误message 等需要稍作修改,它使用 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

于 2012-10-11T18:54:43.290 回答