ASP MVC: Custom Validation Attribute

前端 未结 7 984
说谎
说谎 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条回答
  •  甜味超标
    2021-01-18 10:31

    just as an example:

     using System;
     using System.Collections.Generic;
     using System.ComponentModel.DataAnnotations;
     using System.Globalization;
     using System.Web.Mvc;
     using System.Web.Security;
    
     namespace GDNET.Web.Mvc.Validation
     {
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
    {
        private const string defaultErrorMessage = "'{0}' must be at least {1} characters long.";
        private readonly int minRequiredPasswordLength = Membership.Provider.MinRequiredPasswordLength;
    
        public ValidatePasswordLengthAttribute()
            : base(defaultErrorMessage)
        {
        }
    
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, minRequiredPasswordLength);
        }
    
        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= minRequiredPasswordLength);
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[]
            {
                new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), minRequiredPasswordLength, int.MaxValue)
            };
        }
    }
      }
    

    source: https://code.google.com/p/gdnetprojects/source/browse/trunk/Experiments/Common/GDNET.Web.Mvc/Validation/ValidatePasswordLengthAttribute.cs?r=69

提交回复
热议问题