Ben*_*ord 25 c# asp.net-mvc model data-annotations asp.net-mvc-3
如何在MVC.Net中验证模型的最佳方法,我希望接受最小/最大值.
不是字段的单个最小值/最大值.但是单独的字段供用户指定最小值/最大值.
public class FinanceModel{
public int MinimumCost {get;set;}
public int MaximumCost {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
所以我需要确保MinimumCost始终小于最大成本.
Mat*_*hew 28
有一个名为Foolproof的NuGet包,它为您提供这些注释.也就是说 - 编写自定义属性既简单又好.
使用Foolproof看起来像:
public class FinanceModel{
public int MinimumCost {get;set;}
[GreaterThan("MinimumCost")]
public int MaximumCost {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
小智 23
您可以使用自定义验证属性,这是我的日期示例.但你也可以使用它.
首先,这是模型:
public DateTime Beggining { get; set; }
[IsDateAfterAttribute("Beggining", true, ErrorMessageResourceType = typeof(LocalizationHelper), ErrorMessageResourceName = "PeriodErrorMessage")]
public DateTime End { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是属性本身:
public sealed class IsDateAfterAttribute : ValidationAttribute, IClientValidatable
{
private readonly string testedPropertyName;
private readonly bool allowEqualDates;
public IsDateAfterAttribute(string testedPropertyName, bool allowEqualDates = false)
{
this.testedPropertyName = testedPropertyName;
this.allowEqualDates = allowEqualDates;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
if (propertyTestedInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
}
var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
if (value == null || !(value is DateTime))
{
return ValidationResult.Success;
}
if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
{
return ValidationResult.Success;
}
// Compare values
if ((DateTime)value >= (DateTime)propertyTestedValue)
{
if (this.allowEqualDates && value == propertyTestedValue)
{
return ValidationResult.Success;
}
else if ((DateTime)value > (DateTime)propertyTestedValue)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessageString,
ValidationType = "isdateafter"
};
rule.ValidationParameters["propertytested"] = this.testedPropertyName;
rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
yield return rule;
}
Run Code Online (Sandbox Code Playgroud)
对于使用allowEqualDates和propertyTested参数的客户端验证(补充上面的Boranas答案,但评论太长):
// definition for the isdateafter validation rule
if ($.validator && $.validator.unobtrusive) {
$.validator.addMethod('isdateafter', function (value, element, params) {
value = Date.parse(value);
var otherDate = Date.parse($(params.compareTo).val());
if (isNaN(value) || isNaN(otherDate))
return true;
return value > otherDate || (value == otherDate && params.allowEqualDates);
});
$.validator.unobtrusive.adapters.add('isdateafter', ['propertytested', 'allowequaldates'], function (options) {
options.rules['isdateafter'] = {
'allowEqualDates': options.params['allowequaldates'],
'compareTo': '#' + options.params['propertytested']
};
options.messages['isdateafter'] = options.message;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37784 次 |
| 最近记录: |