ASP MVC: Custom Validation Attribute

前端 未结 7 924
说谎
说谎 2021-01-18 10:00

I\'m trying to write my own Custom Validation attribute but I\'m having some problems.

The attribute I\'m trying to write is that when a user logs in, the password w

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 10:19

    I don't know why this is made out to be such a big deal, just do this:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public class ComparePassword: ValidationAttribute
    {
        public ComparePassword() 
            : base("Passwords must match.") { }
    
        protected override ValidationResult IsValid (object value, ValidationContext validationContext)
        {
            if (value == null) return new ValidationResult("A password is required.");
    
            // Make sure you change YourRegistrationModel to whatever  the actual name is
            if ((validationContext.ObjectType.Name != "YourRegistrationModel") 
                 return new ValidationResult("This attribute is being used incorrectly.");
            if (((YourRegistrationModel)validationContext.ObjectInstance).ConfirmPassword != value.ToString())
                return new ValidationResult("Passwords must match.");
    
            return ValidationResult.Success;
        }
    }
    

    Now all you need to do is add [ComparePassword] to your password property, nothing to pass... simple and fairly clean

提交回复
热议问题