我正在尝试创建一个新的自定义验证,我可以在其中比较同一个类中的两个值。在这种情况下,它检查当人们更改他们的电子邮件时,他们必须输入两次并且这两个值匹配。 (对于添加/更改密码也会这样做)
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; }
}
答案 0 :(得分:1)
您可以使用一些数据注释扩展,目前正在处理更多,因此您不必重新发明轮子。点击链接http://weblogs.asp.net/srkirkland/archive/2011/02/23/introducing-data-annotations-extensions.aspx 您所要做的就是使用Nuget将扩展添加到项目中,并且您已准备好使用内置注释的扩展。干杯!