int*_*ern 9 c# asp.net asp.net-mvc
我想在两个属性之间放置一个规则,即一个属性必须大于另一个属性.那么什么是数据验证属性可以让我这样做?
这是我的财产
public int Min{get;set;}
public int Max{get;set;}
Run Code Online (Sandbox Code Playgroud)
你可以很容易地理解Max必须大于Min.
谢谢您的帮助!
Ale*_*exC 21
对象的数据验证让我感到高兴(以及使用客户端验证).
这是一个可用于执行所要求的属性(可以比较实现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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以装饰你的模型:
public int Min{get;set;}
[GreaterThan("Min")]
public int Max{get;set;}
Run Code Online (Sandbox Code Playgroud)
这是一个有用的问题,关于低于验证MVC自定义验证:比较两个日期但适用于日期而不是整数但适用相同的方法
您可以使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器动作:
[HttpPost]
public ActionResult Test(TestCompareModel viewModel)
{
if (!ModelState.IsValid)
return View(viewModel);
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
视图
@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>
Run Code Online (Sandbox Code Playgroud)
您需要的功能可以使用 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>
Run Code Online (Sandbox Code Playgroud)
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(''); }
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11699 次 |
| 最近记录: |