2

我正在尝试创建一个新的自定义验证,我可以在其中比较同一类中的两个值。在这种情况下,它检查当人们更改他们的电子邮件时,他们必须输入两次并且这两个值匹配。(添加/更改密码也会这样做)

    public class CompareAttribute : ValidationAttribute
    {
        public string CompareValue { get; set; }

        public override bool IsValid(string value)
      {
        //we not validating if its required or not!
        if (value == null)
            return true;



        return value.ToLower().Equals(CompareValue.ToLower());
       }
     }

这是我上面的验证属性类。然后我尝试在我的课堂上使用它来做这个

[Compare(CompareValue = newEmail, ErrorMessage = "New email and Confirm email do not match")]

但我在 newEmail 上收到错误

错误 3 非静态字段、方法或属性“BensBoxing.Domain.EmailChange.newEmail.get”需要对象引用

我全班都是这样

public class EmailChange : Entity
{
    [DisplayName("Current Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "Current Email is a required field")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string currentEmail { get; set; }

    [DisplayName("New Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "New Email is a required field")]
    [EmailInUse(ErrorMessage = "Email is currently in use")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string newEmail { get; set; }

    [DisplayName("Confirm Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "Confirmed Email is a required field")]
    [Compare(CompareValue = newEmail, ErrorMessage = "New email and Confirm email do not match")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string confirmEmail { get; set; }

}
4

1 回答 1

1

您可以使用一些数据注释扩展,并且目前正在开发更多,因此您不必重新发明轮子。按照链接http://weblogs.asp.net/srkirkland/archive/2011/02/23/introducing-data-annotations-extensions.aspx 您所要做的就是使用 Nuget 将扩展添加到您的项目中准备好使用那些内置的注释。干杯!

于 2011-03-19T20:47:17.613 回答