简体   繁体   English

KendoUI,淘汰赛,字段的条件验证

[英]KendoUI, Knockout, conditional validation of a field

I am using kendoui widgets with knockoutjs for datasource. 我正在使用带有kennoutjs的kendoui小部件作为数据源。 I have a checkbox that is data bound to StartClientFromWebEnabled observable variable. 我有一个复选框,该复选框是绑定到StartClientFromWebEnabled可观察变量的数据。 An input text box is visible only when the checkbox ic checked ( StartClientFromWebEnabled is true). StartClientFromWebEnabled复选框ic( StartClientFromWebEnabled为true)时,输入文本框才可见。 The input has a required attribute. 输入具有必填属性。 I want the required validation to be triggered only when the checkbox is checked. 我希望仅在选中复选框时才触发所需的验证。

Here is my html: 这是我的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>

I tried some scenarios including setting onChange event on the checkbox with the following javascript function adding and removing the required attribute: 我尝试了一些方案,包括使用以下javascript函数添加和删除必需的属性在复选框上设置onChange event

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

The problem is I will need this functionality for many dependent properties in my application and my option is to make this function generic with some parameters and call it from the html with the corresponding paramater values like this: 问题是我需要为我的应用程序中的许多依赖属性提供此功能,我的选择是使此函数具有某些参数通用,并使用如下所示的相应参数值从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')" />

I really do not like this scenario. 我真的不喜欢这种情况。 I wonder is there something like a conditional validation in kendoui that trigger only when some condition is satisfied. 我想知道kendoui中是否有类似条件验证的东西,只有在满足某些条件时才会触发。 Any other suggestions are also welcome. 也欢迎任何其他建议。

I had the same issue, I created a custom validator which also handles the server side validation, this example is not 100% complete but all the validation is working, this validates the string length dependant on a checkbox state, it also uses resources for error message etc so will need a little modification, it uses the kendo ui validation client side, let me know if this is useful: 我遇到了同样的问题,我创建了一个自定义验证器,该验证器还处理服务器端验证,此示例并非100%完成,但所有验证都在工作,它根据复选框状态验证字符串长度,并且还会使用错误资源消息等,因此需要进行一些修改,它使用kendo ui验证客户端,请告诉我这是否有用:

Model Properties: 型号属性:

public bool ValidateTextField { get; set; }

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

Custom Validator: 自定义验证器:

[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: 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);

Helpful posts: 有用的帖子:

http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC-3 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 http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM