Customized StringLength Validation doesn't wor

2019-08-12 07:26发布

I added Customized StringLength class in my project

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);
    }
}
}

It's my class CreateUserDto

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

And it's my controller

[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) });
    }

but if I try to enter the password is less than 5 characters or more than 20, ModelState.IsValid == false, but I don't get any error message when the password is less than 5 characters or more than 20. What's wrong?

0条回答
登录 后发表回答