String MinLength and MaxLength validation don't work (asp.net mvc)

前端 未结 5 2009
慢半拍i
慢半拍i 2020-12-12 20:27

I have this class

using System.ComponentModel.DataAnnotations;
using Argussoft.BI.DAL.Domain.Users;

namespace Argussoft.BI.DAL.DTOs.UserDTOs
{
    public cl         


        
相关标签:
5条回答
  • 2020-12-12 20:55

    MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

    From MSDN:

    Specifies the maximum length of array or string data allowed in a property.

    StringLength is a data annotation that will be used for validation of user input.

    From MSDN:

    Specifies the minimum and maximum length of characters that are allowed in a data field.

    Non Customized

    Use [String Length]

    [RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
    [Required(ErrorMessage = "Required")]
    [StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]
    

    30 is the Max Length
    Minimum length = 3

    Customized StringLengthAttribute Class

    public class MyStringLengthAttribute : StringLengthAttribute
    {
        public MyStringLengthAttribute(int maximumLength)
            : base(maximumLength)
        {
        }
    
        public override bool IsValid(object value)
        {
            string val = Convert.ToString(value);
            if (val.Length < base.MinimumLength)
                base.ErrorMessage = "Minimum length should be 3";
            if (val.Length > base.MaximumLength)
                base.ErrorMessage = "Maximum length should be 6";
            return base.IsValid(value);
        }
    }
    
    public class MyViewModel
    {
        [MyStringLength(6, MinimumLength = 3)]
        public String MyProperty { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-12 21:05
        [StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
        [Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
        public string Password { get; set; }
    

    Save resource like this

    "ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"
    
    0 讨论(0)
  • 2020-12-12 21:07

    This can replace the MaxLength and the MinLength

    [StringLength(40, MinimumLength = 10 , ErrorMessage = "Password cannot be longer than 40 characters and less than 10 characters")]
    
    0 讨论(0)
  • 2020-12-12 21:12

    They do now, with latest version of MVC (and jquery validate packages). mvc51-release-notes#Unobtrusive

    Thanks to this answer for pointing it out!

    0 讨论(0)
  • 2020-12-12 21:18

    Try using this attribute, for example for password min length:

    [StringLength(100, ErrorMessage = "Максимальная длина пароля 20 символов", MinimumLength = User.PasswordMinLength)]
    
    0 讨论(0)
提交回复
热议问题