我正在使用带有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中的条件验证是否仅在满足某些条件时触发。任何其他建议也欢迎。
答案 0 :(得分:0)
我有同样的问题,我创建了一个自定义验证器,它也处理服务器端验证,这个例子不是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