Using DataAnnotations to compare two model properties

后端 未结 6 868
你的背包
你的背包 2020-12-03 02:23

How would I go about writing a custom ValidationAttribute that compares two fields? This is the common \"enter password\", \"confirm password\" scenario. I need to be sure t

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 03:14

    This is a longer version of Darin's answer:

    public class CustomAttribute : ValidationAttribute
    {    
        public override bool IsValid(object value)
        {
            if (value.GetType() == typeof(Foo))
            {
               Foo bar = (Foo)value;
               //compare the properties and return the result
            }
    
            throw new InvalidOperationException("This attribute is only valid for Foo objects");
        }
    }
    

    and usage:

    [MetadataType(typeof(FooMD))]
    public partial class Foo
    {
         ... functions ...
    }
    
    [Custom]
    public class FooMD
    {
         ... other data annotations ...
    }
    

    The error will display in @Html.ValidationSummary(false)

提交回复
热议问题