use*_*349 30 asp.net-mvc data-annotations asp.net-mvc-4
我的模型中有这两个字段:
[Required(ErrorMessage="The start date is required")]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime startDate { get; set; }
[Required(ErrorMessage="The end date is required")]
[Display(Name="End Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime endDate{ get; set; }
Run Code Online (Sandbox Code Playgroud)
我要求endDate必须大于startDate.我试过使用,[Compare("startDate")]但这只适用于相同的操作.
我应该用什么来做"大于"的操作?
Dav*_*trg 57
看看Fluent验证或MVC Foolproof验证:这些可以帮助你很多.
例如,使用Foolproof,[GreaterThan("StartDate")]您可以在日期属性上使用注释.
或者,如果您不想使用其他库,则可以通过IValidatableObject在模型上实现来实现自己的自定义验证:
public class ViewModel: IValidatableObject
{
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (EndDate < StartDate)
{
yield return
new ValidationResult(errorMessage: "EndDate must be greater than StartDate",
memberNames: new[] { "EndDate" });
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mah*_*bub 11
IValidatableObject接口为验证对象提供了一种实现IValidatableObject.Validate(ValidationContext validationContext)方法的方法.此方法始终返回IEnumerable对象.这就是为什么你应该创建ValidationResult对象的列表,并将错误添加到此并返回.空列表表示验证您的条件.在mvc 4中如下...
public class LibProject : IValidatableObject
{
[Required(ErrorMessage="Project name required")]
public string Project_name { get; set; }
[Required(ErrorMessage = "Job no required")]
public string Job_no { get; set; }
public string Client { get; set; }
[DataType(DataType.Date,ErrorMessage="Invalid Date")]
public DateTime ExpireDate { get; set; }
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
List < ValidationResult > res =new List<ValidationResult>();
if (ExpireDate < DateTime.Today)
{
ValidationResult mss=new ValidationResult("Expire date must be greater than or equal to Today");
res.Add(mss);
}
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51575 次 |
| 最近记录: |