C# 试图了解如何将变量传递给CustomValidation?
我试图了解如何将数据传递给我创建的自定义验证 我有这个型号C# 试图了解如何将变量传递给CustomValidation?,c#,asp.net-mvc,asp.net-mvc-5,C#,Asp.net Mvc,Asp.net Mvc 5,我试图了解如何将数据传递给我创建的自定义验证 我有这个型号 public class MyModel { [Required(ErrorMessage="Please enter a Start Date")] public DateTime StartDate { get; set; } [Required(ErrorMessage="Please enter an End Date")] [CustomValidation(typeof(DateComp
public class MyModel
{
[Required(ErrorMessage="Please enter a Start Date")]
public DateTime StartDate { get; set; }
[Required(ErrorMessage="Please enter an End Date")]
[CustomValidation(typeof(DateCompareValidation), "ValidateDates")]
public DateTime EndDate { get; set; }
}
这是我的验证器
public class DateCompareValidation
{
public static ValidationResult ValidateDates(object value, ValidationContext context)
{
return new ValidationResult("You are wrong");
}
}
我第一次使用publicstaticvalidationresult ValidateDates()时,它出错了
"..must match the expected signature: public static ValidationResult ValidateDates(object value, ValidationContext context)."
所以我添加了必要的参数
现在调试类时,我看到变量“value”有我的结束日期。
我不太明白它是如何知道它需要什么参数的。
此外,我想知道如何传递开始日期或MyModel类,以便处理验证逻辑?这可能会对您有所帮助
class CustomLengthValidatorAttribute : ValidationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomLengthValidatorAttribute" /> class.
/// </summary>
/// <param name="maxLength">The maximum length.</param>
public CustomLengthValidatorAttribute(int maxLength)
{
this.MaxLength = maxLength;
}
/// <summary>
/// Gets the minimum length.
/// </summary>
/// <value>
/// The minimum length.
/// </value>
public int MaxLength { get; private set; }
/// <summary>
/// Validates the specified value with respect to the current validation attribute.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">The context information about the validation operation.</param>
/// <returns>
/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
/// </returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string fieldName = validationContext.MemberName;
if (Convert.ToString(value).Trim().Length > this.MaxLength)
{
return new ValidationResult(this.ErrorMessage = fieldName + " should not be longer than " + this.MaxLength + " character");
}
return ValidationResult.Success;
}
}
class CustomLengthValidatorAttribute:ValidationAttribute
{
///
///初始化类的新实例。
///
///最大长度。
公共CustomLengthValidator属性(int maxLength)
{
this.MaxLength=MaxLength;
}
///
///获取最小长度。
///
///
///最小长度。
///
public int MaxLength{get;private set;}
///
///验证与当前验证属性相关的指定值。
///
///要验证的值。
///有关验证操作的上下文信息。
///
///类的实例。
///
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
string fieldName=validationContext.MemberName;
if(Convert.ToString(value).Trim().Length>this.MaxLength)
{
返回新的ValidationResult(this.ErrorMessage=fieldName+“长度不应超过”+this.MaxLength+“字符”);
}
返回ValidationResult.Success;
}
}
虽然它不能准确回答您的问题,但我建议您看看。
它可以用流畅的语法接口(使用用户定义的验证程序类)完全取代内置的ASP.NET MVC基于属性的验证
例如,如果要验证StartDate
在EndDate
之前,它可能看起来像:
// validator class for your view model
public class MyModelValidator : AbstractValidator<MyModel>
{
public MyModelValidator()
{
RuleFor(m => m.EndDate).NotNull().WithMessage("Please enter an End Date");
RuleFor(m => m.StartDate).NotNull().WithMessage("Please enter a Start Date")
.LessThan(m => m.EndDate).WithMessage("Start Date must preceed End Date");
}
}
// declare MyModelValidator as a validator for view model
[Validator(typeof(MyModelValidator))]
public class MyModel
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
将逻辑添加到类中并实现IValidateObject怎么样
public class MyClass : IValidatableObject
{
[Required(ErrorMessage="Please enter a Start Date")]
public DateTime? StartDate { get; set; }
[Required(ErrorMessage="Please enter an End Date")]
public DateTime? EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (EndDate < StartDate)
{
yield return new ValidationResult("Invalid date range: End date must be greater then the Start Date");
}
}
}
公共类MyClass:IValidatableObject
{
[必需(ErrorMessage=“请输入开始日期”)]
公共日期时间?开始日期{get;set;}
[必需(ErrorMessage=“请输入结束日期”)]
公共日期时间?结束日期{get;set;}
公共IEnumerable验证(ValidationContext上下文)
{
如果(结束日期<开始日期)
{
返回新的ValidationResult(“无效日期范围:结束日期必须大于开始日期”);
}
}
}
您希望属性做什么?比较DateTime
是否大于StartDate
?是。在这种情况下,我只想确保输入了有效的日期。一旦我了解了这一切是如何工作的,我可能需要编写更复杂的验证器。我建议您阅读
public class MyClass : IValidatableObject
{
[Required(ErrorMessage="Please enter a Start Date")]
public DateTime? StartDate { get; set; }
[Required(ErrorMessage="Please enter an End Date")]
public DateTime? EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (EndDate < StartDate)
{
yield return new ValidationResult("Invalid date range: End date must be greater then the Start Date");
}
}
}