2011-01-13 67 views
0

我有一个搜索表单,可以在两个字段之一上搜索。只有一个是必需的。有没有办法在MVC提供的验证中干净地做到这一点?我可以动态关闭MVC验证吗?

+0

但是,具体而言,一个是所需的路程和其他可选的路线,或者是两者中的一个应该被填充,而不是关心哪一个? – FelixMM 2011-01-13 22:45:00

回答

0

如果这是服务器的验证,你可以为此创建自定义验证属性:

[ConditionalRequired("Field1","Field2")] 
public class MyModel() 
{ 
    public string Field1 { get; set; } 
    public string Field2 { get; set; } 
} 

然后您可以创建一个自定义的验证属性..类似以下内容:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class ConditionalRequiredAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "Either '{0}' or '{1}' must be provided."; 
    public string FirstProperty { get; private set; } 
    public string SecondProperty { get; private set; } 

    public ConditionalRequiredAttribute(string first, string second) 
     : base(_defaultErrorMessage) 
    { 
     FirstProperty = first; 
     SecondProperty = second; 
    } 
    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      FirstProperty, SecondProperty); 
    } 

    public override bool IsValid(object value) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     string originalValue = properties.Find(FirstProperty, true).GetValue(value).ToString(); // ToString() MAY through a null reference exception.. i haven't tested it at all 
     string confirmValue = properties.Find(SecondProperty, true).GetValue(value).ToString(); 
     return !String.IsNullOrWhiteSpace(originalValue) || !String.IsNullOrWhiteSpace(confirmValue); // ensure at least one of these values isn't null or isn't whitespace 
    } 
} 

其有点冗长,但它使您可以灵活地将此属性直接应用于您的模型,而不是将其应用到每个单独的字段