2012-10-11 169 views
0

我使用kendoui部件與knockoutjs爲數據源的條件驗證。我有一個數據綁定到StartClientFromWebEnabled可觀察變量的複選框。輸入文本框僅在複選框ic被選中時纔可見(StartClientFromWebEnabled爲真)。輸入具有必需的屬性。我希望僅在複選框被選中時觸發所需的驗證。KendoUI,淘汰賽,場

這裏是我的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> 

我嘗試了一些方案,包括用下面的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"); 
    } 
} 

的問題是,我會需要此功能,在我的應用程序依賴於很多屬性和我的選擇是讓這個功能一般用一些參數和從HTML像這樣相應paramater值叫它:

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

我有同樣的問題,我創建了一個自定義的驗證也可以用來處理在服務器端驗證,這個例子是不是100%完成,但所有驗證工作,這驗證依賴於一個複選框狀態字符串的長度,這也使用資源的錯誤信息等,從而將需要稍加修改,它採用了劍道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

+0

我感興趣的只是在客戶端驗證,我有,我用流利的服務器端驗證沒有問題驗證。我不太瞭解代碼的JavaScript部分與我的情況有關。你能否給我一個示例代碼,我發佈的示例代碼(只有JavaScript部分)。 – Mdb

+0

這可能矯枉過正以滿足您的需求,但服務器端代碼會將屬性添加到javascript使用的複選框和文本框中。當劍道驗證觸發它首先獲取文本框的「VAL-checkboxdependantvalidator-checkboxid」屬性,使用它來獲取複選框的狀態,那麼驗證文本如果需要的話。 – Neepheed