我可以在MVC中动态关闭验证吗?

时间:2011-01-13 19:39:34

标签: asp.net-mvc

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

1 个答案:

答案 0 :(得分: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
    }
}

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