我的用户模型有这些数据注释来验证输入字段:
[Required(ErrorMessage = "Username is required")]
[StringLength(16, ErrorMessage = "Must be between 3 and 16 characters", MinimumLength = 3)]
public string Username { get; set; }
[Required(ErrorMessage = "Email is required"]
[StringLength(16, ErrorMessage = "Must be between 5 and 50 characters", MinimumLength = 5)]
[RegularExpression("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$", ErrorMessage = "Must be a valid email")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required"]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is required"]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
public string ConfirmPassword { get; set; }
但是,我无法确定如何确保确认密码与密码相同。据我所知,只有这些验证例程存在:Required, StringLength, Range, RegularExpression
。
我可以在这里做什么?谢谢。
最佳答案
如果您使用的是 ASP.Net MVC 3
,则可以使用 System.Web.Mvc.CompareAttribute
。
如果您使用的是 ASP.Net 4.5
,它位于 System.Component.DataAnnotations
中。
[Required(ErrorMessage = "Password is required")]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
编辑:对于 MVC2
使用下面的逻辑,使用 PropertiesMustMatch
代替 Compare
属性 [下面的代码是从默认的 MVCApplication 复制的
项目模板。]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
关于c# - 用于验证确认密码的数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13237193/