C# 用于验证确认密码的数据注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13237193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:52:12  来源:igfitidea点击:

Data Annotation to validate confirm password

c#asp.netdata-annotations

提问by James Dawson

My User model has these data annotations to validate input fields:

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

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

However, I'm having trouble working out how to make sure Confirm Password is the same as Password. As far as I know only these validation routines exist: Required, StringLength, Range, RegularExpression.

但是,我无法确定如何确保确认密码与密码相同。据我所知,只有这些验证例程存在:Required, StringLength, Range, RegularExpression.

What can I do here? Thanks.

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

采纳答案by Prasad Kanaparthi

If you are using ASP.Net MVC 3, you can use System.Web.Mvc.CompareAttribute.

如果您正在使用ASP.Net MVC 3,则可以使用System.Web.Mvc.CompareAttribute.

If you are using ASP.Net 4.5, it's in the System.Component.DataAnnotations.

如果您正在使用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; }

EDIT: For MVC2Use the below Logic, Use PropertiesMustMatchinstead Compareattribute [Below code is copied from the default MVCApplicationproject template.]

编辑:对于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);
    }
}

回答by Khursand Kousar

Other data annotations are optional you can add those according to your requirement but you need to do this to implement password comparison operation

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

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

[Required]
[DataType(DataType.Password)]`enter code here`
[Compare("Password")]
public string ConfirmPassword { get; set; }

回答by Mahadi Hasan

You can use the compare annotation to compare two values, and if you need to make sure it isn't persisted anywhere downstream (For example if you are using EF) You can also add NotMapped to ignore any entity->DB mapping

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

For a full list of data annotations available, see here:

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

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

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