2014-04-10 61 views
0

我在我的表單上有兩個datepickers字段,我想驗證到目前爲止大於從日期。MVC5驗證 - 迄今爲止大於日期

MVC5中有任何驗證屬性,我可以用它來實現這個嗎?

我也想這樣做在客戶端,可以請一些身體幫助在MVC中啓用客戶端驗證?

非常感謝

編輯:創建自定義屬性,但是客戶端驗證無法正常工作。

public class ValidateToDateAttribute : ValidationAttribute, IClientValidatable 
    { 

     public string errorMessageKey { get; private set; } 

     public ValidateToDateAttribute(string errorMessageKey) 
     { 
      this.errorMessageKey = errorMessageKey; 
     } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      if (value != null) 
      { 
       var viewModel = (TransactionViewModel)validationContext.ObjectInstance; 
       if (viewModel.ToDate.CompareTo(viewModel.FromDate) < 0) 
       { 
        return new ValidationResult(new ResourceManager(typeof(ValidationErrorMessages)).GetString(errorMessageKey)); 
       } 
      } 

      return ValidationResult.Success; 
     } 

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
     { 
      var modelClientValidationRule = new ModelClientValidationRule 
      { 
       ValidationType = "validatetodate", 
       ErrorMessage = new ResourceManager(typeof(ValidationErrorMessages)).GetString(errorMessageKey) 
      }; 

      yield return modelClientValidationRule; 
     } 
    } 
} 

Bundle.Config

bundles.Add(new ScriptBundle("~/bundles/jqueryvalidation").Include(
         "~/Scripts/jquery.validate.unobtrusive.min.js", 
         "~/Scripts/jquery.unobtrusive-ajax.min.js")); 

視圖模型

[Display(ResourceType = typeof(DisplayLabelText), Name = "FromDate")]  
    public DateTime FromDate { get; set; } 

    [Display(ResourceType = typeof(DisplayLabelText), Name = "ToDate")] 
    [ValidateToDate("ToDateMustBeGreater")] 
    public DateTime ToDate { get; set; } 

在查看:

<div class="col-sm-7 margin-top-10"> 
         <div class="col-sm-12"> 
          @Html.LabelFor(m => m.FromDate, new { @class = "col-sm-3 form-group control-label" }) 
          <div class="col-sm-8"> 
           @Html.TextBoxFor(m => m.FromDate, "{0:MMM dd yyyy}", new { @class = "datepicker", disabled = "disabled" }) 
          </div> 
         </div> 
         <div class="col-sm-12"> 
          @Html.LabelFor(m => m.ToDate, new { @class = "col-sm-3 form-group control-label" }) 
          <div class="col-sm-8"> 
           @Html.TextBoxFor(m => m.ToDate, "{0:MMM dd yyyy}", new { @class = "datepicker", disabled = "disabled" }) 
           @Html.ValidationMessageFor(m => m.ToDate) 
          </div> 
         </div> 
         <button type="submit" class="apply-filter-button">Apply Filter</button> 
        </div> 
+0

我們不是在這裏爲您提供完整的教程或做所有的工作/研究爲您的。我們主要是在這裏幫助你寫一段你寫的代碼或回答一個簡明的問題。請參閱:http://stackoverflow.com/help/how-to-ask – Sparky

+0

爲什麼在詢問MVC5時如何使用MVC3和MVC4標籤?這裏不允許使用標籤發送垃圾郵件。 – Sparky

+2

沒有意圖標記垃圾郵件,我只是認爲mvc3和mvc4的解決方案可能仍然適用於MVC5。 – Vin05

回答

0

我想通了,我錯過了不顯眼的Java腳本代碼: 請參閱b對於某些人來說,這可能會有幫助。

public class ValidateToDateAttribute : ValidationAttribute, IClientValidatable 
{  
    /// <summary> 
    /// Initializes a new instance of the <see cref="ValidateToDateAttribute"/> class. 
    /// </summary> 
    /// <param name="errorMessageKey">The error message key.</param> 
    public ValidateToDateAttribute(string errorMessageKey, string otherProperty) 
    { 
     this.ErrorMessageKey = errorMessageKey; 
     this.FromDate = otherProperty; 
    } 

    /// <summary> 
    /// Gets from date. 
    /// </summary> 
    /// <value> 
    /// From date. 
    /// </value> 
    public string FromDate { get; private set; } 

    /// <summary> 
    /// Gets the error message key. 
    /// </summary> 
    /// <value> 
    /// The error message key. 
    /// </value> 
    public string ErrorMessageKey { get; private set; } 

    /// <summary> 
    /// When implemented in a class, returns client validation rules for that class. 
    /// </summary> 
    /// <param name="metadata">The model metadata.</param> 
    /// <param name="context">The controller context.</param> 
    /// <returns> 
    /// The client validation rules for this validator. 
    /// </returns> 
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var modelClientValidationRule = new ModelClientValidationRule 
     { 
      ValidationType = "validatetodate", 
      ErrorMessage = new ResourceManager(typeof(ValidationErrorMessages)).GetString(this.ErrorMessageKey),    
     }; 

     modelClientValidationRule.ValidationParameters.Add("other", this.FromDate); 
     yield return modelClientValidationRule; 
    } 

    /// <summary> 
    /// Validates the specified value with respect to the current validation attribute. 
    /// </summary> 
    /// <param name="value">The value to validate.</param> 
    /// <param name="validationContext">The context information about the validation operation.</param> 
    /// <returns> 
    /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class. 
    /// </returns> 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     if (value != null) 
     { 
      var viewModel = (TransactionViewModel)validationContext.ObjectInstance; 
      if (viewModel.ToDate.CompareTo(viewModel.FromDate) < 0) 
      { 
       return new ValidationResult(new ResourceManager(typeof(ValidationErrorMessages)).GetString(this.ErrorMessageKey)); 
      } 
     } 

     return ValidationResult.Success; 
    } 
} 

的JavaScript:

<script type="text/javascript"> 
jQuery.validator.addMethod('greaterThan', function (value, element, params) {   
    if (!/Invalid|NaN/.test(new Date(value))) { 
     //return new Date(value) > new Date($("input[name='FromDate']").val());    
     return Date.parse(value) > Date.parse($(params).val()); 
    }  
    return isNaN(value) && isNaN($(fromDate)) || (parseFloat(value) > parseFloat($("input[name='FromDate']").val())); 
}, ''); 

// and an unobtrusive adapter 
jQuery.validator.unobtrusive.adapters.add('validatetodate', ["other"], function (options) {  
    options.rules['greaterThan'] = "#" + options.params.other; 
    options.messages['greaterThan'] = options.message; 
});