2012-05-21 32 views
1

我在我的ASP.NET MVC3项目中有一个自定义ValidationAttribute,它有两个需要满足的条件。它工作的很好,但我想通过返回一个自定义的错误消息来让用户知道哪个验证规则已被破坏。如何创建条件ValidationAttribute错误消息?

由于我使用的(继承基类的错误消息)我知道它已经被初始化后,我无法改变_defaultError常量的值,因此该方法....

我如何返回不同错误消息取决于哪些条件不符合?

这里是我的ValidationAttribute代码:

public class DateValidationAttribute :ValidationAttribute 
{ 
    public DateValidationAttribute() 
     : base(_defaultError) 
    { 

    } 

    private const string _defaultError = "{0} [here is my generic error message]"; 

    public override bool IsValid(object value) 
    { 
     DateTime val = (DateTime)value; 

     if (val > Convert.ToDateTime("13:30:00 PM")) 
     { 
      //This is where I'd like to set the error message 
      //_defaultError = "{0} can not be after 1:30pm"; 
      return false; 
     } 
     else if (DateTime.Now.AddHours(1).Ticks > val.Ticks) 
     { 
      //This is where I'd like to set the error message 
      //_defaultError = "{0} must be at least 1 hour from now"; 
      return false; 
     } 
     else 
     { 
      return true; 
     } 

    } 
} 

回答

1

我可以建议你创建两个不同的实现DateValidator类用于中,各自具有不同的消息。这也符合SRP,因为您只需将每个验证器中的相关验证信息分开。

public class AfternoonDateValidationAttribute : ValidationAttribute 
{ 
    // Your validation logic and message here 
} 

public class TimeValidationAttribute : ValidationAttribute 
{ 
    // Your validation logic and message here 
} 
+0

+1 Thanks Hadi。那就是诀窍。我把它分成两个独立的自定义验证属性,它工作得很完美。关于SRP的优点也是。 – Dhaust