数据注释validation确认密码

我的用户模型有这些数据注释来validationinput字段:

[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; } 

但是,我无法确定如何确认确认密码与密码相同。 据我所知只有这些validation程序存在: 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); } }