我添加定制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 ==假的,但是当密码长度小于5个字符或超过20什么是错了,我没有得到任何错误讯息?