2011-08-17 46 views
0

我有一个有趣的客户端需求。ASP.NET MVC - 两个文本框中的一个验证器

我有需要显示像这样控制:

Date of xxx  [ mm ][ yy ] 

有两个文本框一个标签 - 一个用于月份数字,一个是一年的数字。

虽然有两个文本字段,但我们希望在验证两个字段之后运行验证。

此外,页面上还有许多这些控件。如何将打包这件事的最好方法,这样我可以打电话:

@Laberfor(x => x.Datexxx) 
@EditorFor(x => x.Datexxx) 

在此先感谢

回答

0

如果你的控制是强类型的,你可以实现IValidatableObject及其Validate方法。

假设你的模式是这样的:

public class CombinedDateViewModel : IValidatableObject 
{ 
    [Required] 
    public int month { get; set; } 
    [Required] 
    public int year { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    {   
     if(month > 12 || month < 1) 
      yield return new ValidationResult("Month is out of range"); 
     if(year < 0 || year > 2020) 
      yield return new ValidationResult("Year is out of range"); 
    } 
} 

的产生验证结果将在验证摘要体现。