1

我在我的项目中添加了自定义 StringLength 类

using System;
using System.ComponentModel.DataAnnotations;

namespace Argussoft.BI.DAL.Validation
{
public class PasswordLengthAttribute : StringLengthAttribute
{
    public PasswordLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < MinimumLength)
            ErrorMessage = "Минимальная длина пароля 5 символов";
        if (val.Length > MaximumLength)
            ErrorMessage = "Максимальная длина пароля 20 символов";
        return base.IsValid(value);
    }
}
}

这是我的班级 CreateUserDto

public class CreateUserDto
    {
      [Required(ErrorMessage = "Введите пароль")]
        [PasswordLength(User.PasswordMaxLength, MinimumLength = User.PasswordMinLength)]
        [RegularExpression(User.PasswordRegularExpression, ErrorMessage = "Пароль может содержать только латинские символы, дефисы, подчеркивания, точки")]
        public virtual String Password { get; set; }
    }

这是我的控制器

[HttpPost]
    public ActionResult CreateUser(CreateUserDto dto)
    {
        if (!Request.IsAjaxRequest()) return View("_AddUserDialog", dto);
        if (!ModelState.IsValid) {FillViewBags(); return PartialView("_AddUserDialog", dto);}
        string hash;
        string salt;
        CryptoUtils.SetHashAndSalt(dto.Password, out hash, out salt);
        UserService.CreateUser(
            new User ()
            {
                Name = dto.Name,
                Email = dto.Email,
                FullName = dto.FullName,
                Role = UserService.SetRole(dto.Role),
                Phone = dto.Phone,
                Status = UserService.SetUserStatus(dto.Status),
                PasswordHash = hash,
                PasswordSalt = salt
            });
        return Json(new { Message = string.Format("Пользователь {0} успешно создан", dto.Name) });
    }

但是如果我尝试输入密码少于 5 个字符或多于 20 个字符,ModelState.IsValid == false,但是当密码少于 5 个字符或多于 20 个字符时,我没有收到任何错误消息。怎么了?

4

0 回答 0