2014-09-05 58 views
8

我想在兩個屬性之間放置一個屬性,即一個屬性必須大於另一個屬性。 那麼可以讓我這樣做的數據驗證屬性是什麼?兩個屬性之間的條件的數據驗證屬性asp.net mvc

這裏是我的屬性

public int Min{get;set;} 
    public int Max{get;set;} 

正如你可以很容易地理解馬克斯必須大於最小。

謝謝你的幫助!

+1

使用jQuery,而不是模型驗證 – 2014-09-05 09:06:16

+0

我喜歡模型驗證,我不知道如何處理的Jquery – intern 2014-09-05 09:19:18

+0

Okk..but爲據我瞭解mvc它很難得到你的功能只有辦法是作爲自定義驗證屬性,但使用jquery它非常容易.. – 2014-09-05 09:22:39

回答

1

您需要可以很容易地使用jQuery實現如圖所示的功能: -

HTML: -

<input type="text" id="Max" name="Max" /> //with model validations just make sure user can input numbers in Max and Min textboxes. 
<input type="text" id="Min" name="Min" /> 
<div id="errormess"></div> 

的Jquery:

$(document).ready(function(){ 
    $("#Max").focusout(function(){ 
     if(parseInt($(this).val()) < parseInt($("#Min").val())) 
     { 
     $("#errormess").html('Max value cannot be lower then Min Value'); 
     } 
     else{ $("#errormess").html(''); } 
    }); 

    $("#Min").focusout(function(){ 
     if(parseInt($(this).val()) > parseInt($("#Max").val())) 
     { 
     $("#errormess").html('Max value cannot be lower then Min Value'); 
     } 
     else{ $("#errormess").html(''); } 
    }); 
}); 

DEMO

+0

謝謝你的幫助異常現在更清楚! – intern 2014-09-05 14:39:11

+0

@ intern..your welcome ... – 2014-09-05 14:42:40

1

我同意例外情況,JQuery比模型更容易處理本身用於完成這種功能。然而,據說沒有Javascript/Jquery的經驗值得看一下JQuery here的文檔。

您還可以找到偉大的教程here

而且最重要的部分,實際的jQuery庫文件here。您可以下載該文件並將其包含在您的解決方案中,或者在視圖的標題中簡單包含指向服務器託管的CDN版本文件的鏈接。 (這兩個選項都在我給你的鏈接上提供了說明)

但是,對異常情況的更新答案不包括僅允許輸入控件中的整數值所需的功能。要解決這個問題,只需將input types屬性更改爲「number」就可以了。

<input type="number" id="Max" name="Max" /> 

並修改腳本刪除字符串解析爲整數這樣的:

$("#Max").focusout(function(){ 
     if($(this).val() < $("#Min").val()) 
     { 
     $("#errormess").html('Max value cannot be lower then min Value'); 
     } 
     else{ $("#errormess").html(''); } 
    }); 

    $("#Min").focusout(function(){ 
     if($(this).val() >= $("#Max").val()) 
     { 
     $("#errormess").html('Max value cannot be lower then min Value'); 
     } 
     else{ $("#errormess").html(''); } 
    }); 
+0

非常感謝您的幫助! – intern 2014-09-05 14:38:44

17

在對象上的數據驗證打我是件好事(以及使用客戶端驗證)。

這是你可以用來做你的要求(這將是能夠比較的是實現IComparable的類型對)

public class GreaterThanAttribute : ValidationAttribute 
{ 

    public GreaterThanAttribute(string otherProperty) 
     : base("{0} must be greater than {1}") 
    { 
     OtherProperty = otherProperty; 
    } 

    public string OtherProperty { get; set; } 

    public string FormatErrorMessage(string name, string otherName) 
    { 
     return string.Format(ErrorMessageString, name, otherName); 
    } 

    protected override ValidationResult 
     IsValid(object firstValue, ValidationContext validationContext) 
    { 
     var firstComparable = firstValue as IComparable; 
     var secondComparable = GetSecondComparable(validationContext); 

     if (firstComparable != null && secondComparable != null) 
     { 
      if (firstComparable.CompareTo(secondComparable) < 1) 
      { 
       object obj = validationContext.ObjectInstance; 
       var thing = obj.GetType().GetProperty(OtherProperty); 
       var displayName = (DisplayAttribute)Attribute.GetCustomAttribute(thing, typeof(DisplayAttribute)); 

       return new ValidationResult(
        FormatErrorMessage(validationContext.DisplayName, displayName.GetName())); 
      } 
     } 

     return ValidationResult.Success; 
    } 

    protected IComparable GetSecondComparable(
     ValidationContext validationContext) 
    { 
     var propertyInfo = validationContext 
           .ObjectType 
           .GetProperty(OtherProperty); 
     if (propertyInfo != null) 
     { 
      var secondValue = propertyInfo.GetValue(
       validationContext.ObjectInstance, null); 
      return secondValue as IComparable; 
     } 
     return null; 
    } 
} 

然後,您可以裝飾你的模型屬性:

public int Min{get;set;} 

    [GreaterThan("Min")] 
    public int Max{get;set;} 

這對於除驗證MVC custom validation: compare two dates少一個有用的問題,而是適用於日期,而不是整數,但同樣的方法也適用

+0

我個人很喜歡這種方法。儘管這些日子裏,每個人都可能已經啓用了JavaScript,但仍然是在客戶端和服務器上執行驗證的最佳實踐。如果你只是在一個地方做,我仍然會在服務器端做。你可能應該這樣做,而JQuery解決方案在這個答案下面。 – 2014-09-05 12:11:17

+0

謝謝!你的帖子很有意思 – intern 2014-09-05 14:37:37

4

您合作uld使用一個Attribute或你的視圖模型可以實現IValidatableObject。有什麼不錯的是,asp.net mvc modelbinder會在後期自動運行。

public class TestCompareModel : IValidatableObject 
{ 
    [Required] 
    public Int32 Low { get; set; } 

    [Required] 
    public Int32 High { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     var results = new List<ValidationResult>(); 

     if (High < Low) 
      results.Add(new ValidationResult("High cannot be less than low")); 

     return results; 
    } 
} 

控制器動作:

[HttpPost] 
    public ActionResult Test(TestCompareModel viewModel) 
    { 
     if (!ModelState.IsValid) 
      return View(viewModel); 

     return RedirectToAction("Index"); 
    } 

查看

@model Scratch.Web.Models.TestCompareModel 

@{ 
    ViewBag.Title = "Test"; 
} 

<h2>Test</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>TestCompareModel</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     <div class="form-group"> 
      @Html.LabelFor(model => model.Low, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.Low, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.Low, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.High, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.High, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.High, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 
+0

這應該被標記爲答案!它符合DRY,並在客戶端生成驗證碼。我很滿意需要POST,因爲這種驗證是更多的業務/域驗證。還有更少的代碼寫入(沒有新的屬性類或向視圖添加邏輯)。 – ShooShoSha 2017-08-10 04:25:15

+0

非常感謝你! – 2017-09-26 09:34:39