我需要使用自己的自定义数据注释对MVC 4.5的自定义验证提出一些建议
我在注册网站时验证某人的年龄。
我要求将这些作为字段传递给验证器。
(date) date of birth
(date)event start date
(int)min age value
我将最小年龄和事件开始日期存储在web.config中。所以这可以很容易地定制。 如果用户的年龄在检查事件日期时不够大,那么他们就无法注册。
我该怎么做呢?我已经检查了一些例子,但我似乎无法理解它。
感谢...
答案 0 :(得分:2)
创建自己的验证属性是可行的方法,并且易于实现。要创建一个,您只需要创建一个实现ValidationAttribute
示例强>
public class MinAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Do some validation checks here
var result = new ValidationResult("Sorry you are not old enough");
return result;
}
您覆盖IsValid
方法以执行验证逻辑,返回ValidationResult
答案 1 :(得分:0)
您可以通过实现IValidatableObject接口然后使用Validate方法进行自定义验证。选中“Using IValidatableObject Custom Validation”
请注意,IValidatableObject仅支持服务器端验证。在我看来,最好是进行服务器端验证。以防您在Web服务调用中使用相同的方法。
如果您想要自定义客户端验证,请尝试实现IClientValidatable和ValidationAttribute
答案 2 :(得分:0)
使用 ValidationAttribute 创建自己的注释,并将其装饰为必需的属性。您必须覆盖返回布尔值的 Validate()方法。并在此基础上,您可以执行您的操作
答案 3 :(得分:0)
没有必要仅为年龄验证创建自定义属性。您需要做的就是创建一个自定义属性,从出生日期开始计算年龄,然后在年龄属性上添加一个最小年龄的正常范围验证属性。
但问题是,您在web.config中设置了最小年龄,并且在编译时创建属性,而不是在运行时创建。
我建议使用Fluent验证,因为您可以创建更好的验证方案。
答案 4 :(得分:0)
.net核心上的最小年龄检查属性的示例 用法:[MinAge(18)]
属性:
[AttributeUsage(AttributeTargets.Property)]
public class MinAgeAttribute : ValidationAttribute
{
private readonly int _limit;
private readonly string _messageFormat;
/// <summary>
/// Constructor
/// </summary>
/// <param name="limit"></param>
/// <param name="messageFormat"></param>
public MinAgeAttribute(int limit, string messageFormat = null)
{
_limit = limit;
_messageFormat = messageFormat;
}
/// <summary>
/// Check if valid
/// </summary>
/// <param name="value"></param>
/// <param name="validationContext"></param>
/// <returns></returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var bDay = DateTime.Parse(value.ToString());
var today = DateTime.Today;
var age = today.Year - bDay.Year;
if (bDay > today.AddYears(-age))
{
age--;
}
if (age >= _limit) return null;
var message = _messageFormat.IsNullOrEmpty() ? "Sorry you are not old enough" : string.Format(_messageFormat, _limit);
var result = new ValidationResult(message);
return result;
}
}