我的模型上有一个值,它必须落在模型上另外两个值的范围内。
例如:
public class RangeValidationSampleModel
{
int Value { get; set; }
int MinValue { get; set; }
int MaxValue { get; set; }
}
当然,我不能将这些最小/最大值传递给我的DataAnnotations属性,因为它们必须是常量值。
我确定我需要构建自己的验证属性,但我还没有做这么多,也不知道它应该如何工作。
我已经搜索了大约一个小时,看到了构建自定义验证的各种解决方案,但没有找到任何使用MVC3非侵入性验证来解决这个特定问题的方法。
发布于 2011-10-22 04:27:07
为此,您可以编写一个自定义验证属性:
public class DynamicRangeValidator : ValidationAttribute, IClientValidatable
{
private readonly string _minPropertyName;
private readonly string _maxPropertyName;
public DynamicRangeValidator(string minPropertyName, string maxPropertyName)
{
_minPropertyName = minPropertyName;
_maxPropertyName = maxPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var minProperty = validationContext.ObjectType.GetProperty(_minPropertyName);
var maxProperty = validationContext.ObjectType.GetProperty(_maxPropertyName);
if (minProperty == null)
{
return new ValidationResult(string.Format("Unknown property {0}", _minPropertyName));
}
if (maxProperty == null)
{
return new ValidationResult(string.Format("Unknown property {0}", _maxPropertyName));
}
int minValue = (int)minProperty.GetValue(validationContext.ObjectInstance, null);
int maxValue = (int)maxProperty.GetValue(validationContext.ObjectInstance, null);
int currentValue = (int)value;
if (currentValue <= minValue || currentValue >= maxValue)
{
return new ValidationResult(
string.Format(
ErrorMessage,
minValue,
maxValue
)
);
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "dynamicrange",
ErrorMessage = this.ErrorMessage,
};
rule.ValidationParameters["minvalueproperty"] = _minPropertyName;
rule.ValidationParameters["maxvalueproperty"] = _maxPropertyName;
yield return rule;
}
}
然后用它装饰你的视图模型:
public class RangeValidationSampleModel
{
[DynamicRangeValidator("MinValue", "MaxValue", ErrorMessage = "Value must be between {0} and {1}")]
public int Value { get; set; }
public int MinValue { get; set; }
public int MaxValue { get; set; }
}
然后你可以有一个控制器服务于一个视图:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new RangeValidationSampleModel
{
Value = 5,
MinValue = 6,
MaxValue = 8
});
}
[HttpPost]
public ActionResult Index(RangeValidationSampleModel model)
{
return View(model);
}
}
当然还有一个观点:
@model RangeValidationSampleModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.unobtrusive.adapters.add('dynamicrange', ['minvalueproperty', 'maxvalueproperty'],
function (options) {
options.rules['dynamicrange'] = options.params;
if (options.message != null) {
$.validator.messages.dynamicrange = options.message;
}
}
);
$.validator.addMethod('dynamicrange', function (value, element, params) {
var minValue = parseInt($('input[name="' + params.minvalueproperty + '"]').val(), 10);
var maxValue = parseInt($('input[name="' + params.maxvalueproperty + '"]').val(), 10);
var currentValue = parseInt(value, 10);
if (isNaN(minValue) || isNaN(maxValue) || isNaN(currentValue) || minValue >= currentValue || currentValue >= maxValue) {
var message = $(element).attr('data-val-dynamicrange');
$.validator.messages.dynamicrange = $.validator.format(message, minValue, maxValue);
return false;
}
return true;
}, '');
</script>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Value)
@Html.EditorFor(x => x.Value)
@Html.ValidationMessageFor(x => x.Value)
</div>
<div>
@Html.LabelFor(x => x.MinValue)
@Html.EditorFor(x => x.MinValue)
</div>
<div>
@Html.LabelFor(x => x.MaxValue)
@Html.EditorFor(x => x.MaxValue)
</div>
<button type="submit">OK</button>
}
显然,自定义适配器注册应该在外部javascript文件中执行,以避免污染视图,但为了这篇文章的目的和简明性,我将其放在视图中。
发布于 2011-10-21 22:59:14
自定义验证属性确实是一个很好的想法。就像这样(我挖出了一些片段,谁知道不久前在哪里找到的):
public sealed class MustBeGreaterThan : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be greater than '{1}'";
private string _basePropertyName;
public MustBeGreaterThan(string basePropertyName)
: base(_defaultErrorMessage)
{
_basePropertyName = basePropertyName;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
return string.Format(_defaultErrorMessage, name, _basePropertyName);
}
//Override IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
var lowerBound = (int)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisValue = (int)value;
if (thisValue < lowerBound)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//value validated
return null;
}
}
public sealed class MustBeLowerThan : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be lower than '{1}'";
private string _basePropertyName;
public MustBeLowerThan(string basePropertyName)
: base(_defaultErrorMessage)
{
_basePropertyName = basePropertyName;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
return string.Format(_defaultErrorMessage, name, _basePropertyName);
}
//Override IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
var upperBound = (int)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisValue = (int)value;
if (thisValue > upperBound)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//value validated
return null;
}
}
然后装饰你的类
public class RangeValidationSampleModel
{
[MustBeGreaterThan("MinValue")]
[MustBeLowerThan("MaxValue")]
int Value { get; set; }
int MinValue { get; set; }
int MaxValue { get; set; }
}
你应该可以走了
发布于 2011-10-21 23:02:15
如果您需要客户端验证,这将必须是自定义的。我最近在这里看到了一篇不错的帖子(Darin Dmitrov?似乎找不到它)任何方式-这将允许客户端验证发生:http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
服务器端可以通过IValidateableObject或Dynamic Range Validation in ASP.NET MVC 2进行处理
在服务器端等等,但我觉得你想让客户端成为关键。
https://stackoverflow.com/questions/7851035
复制相似问题