63

我的用户模型有这些数据注释来验证输入字段:

[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.

我可以在这里做什么?谢谢。

4

4 回答 4

135

如果你正在使用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);
    }
}
于 2012-11-05T17:28:26.350 回答
8

您可以使用 compare 注释来比较两个值,如果您需要确保它不会在下游任何地方持久化(例如,如果您使用的是 EF)您还可以添加 NotMapped 以忽略任何实体-> DB 映射

有关可用数据注释的完整列表,请参见此处:

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[Compare("Password")]
[NotMapped]
public string ConfirmPassword { get; set; }
于 2018-06-29T18:57:41.113 回答
0

对于 BlazorEditForm验证

上面的答案对我不起作用,因为它没有显示任何消息。


    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public sealed class PropertyMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";

        public PropertyMustMatchAttribute(string originalProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
        }
        
        public string OriginalProperty { get; }

        protected override ValidationResult IsValid(object value,
            ValidationContext validationContext)
        {
            var properties = TypeDescriptor.GetProperties(validationContext.ObjectInstance);
            var originalProperty = properties.Find(OriginalProperty, false);
            var originalValue = originalProperty.GetValue(validationContext.ObjectInstance);
            var confirmProperty = properties.Find(validationContext.MemberName, false);
            var confirmValue = confirmProperty.GetValue(validationContext.ObjectInstance);
            if (originalValue == null)
            {
                if (confirmValue == null)
                {
                    return ValidationResult.Success;
                }

                return new ValidationResult(ErrorMessage,
                    new[] { validationContext.MemberName });
            }

            if (originalValue.Equals(confirmValue))
            {
                return ValidationResult.Success;
            }

            return new ValidationResult(ErrorMessage,
                new[] { validationContext.MemberName });
        }
    }
于 2021-10-16T21:34:04.190 回答
0

其他数据注释是可选的。您可以根据需要添加这些,但您需要这样做以实现密码比较操作。

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
于 2018-03-19T06:12:47.233 回答