How to validate two properties with ASP.NET MVC 2

后端 未结 1 1300
难免孤独
难免孤独 2020-12-17 02:09

I\'m just getting started with ASP.NET MVC 2, and playing around with Validation.

Let\'s say I have 2 properties:

  • Password1
  • Password2
相关标签:
1条回答
  • 2020-12-17 02:44

    The default ASP.NET MVC 2 template of Visual Studio includes the exact validation attribute you need. Pasted from AccountModels.cs file :

    [AttributeUsage(AttributeTargets.Class, 
        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);
        }
    }
    

    How to use :

    [PropertiesMustMatch("Password", "ConfirmPassword", 
        ErrorMessage = "The password and confirmation password do not match.")]
    class NewUser {
        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Confirm password")]
        public string ConfirmPassword { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题