【问题标题】:String MinLength and MaxLength validation don't work (asp.net mvc)字符串 MinLength 和 MaxLength 验证不起作用(asp.net mvc)
【发布时间】:2013-08-19 01:39:18
【问题描述】:

我有这门课

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

namespace Argussoft.BI.DAL.DTOs.UserDTOs
{
    public class CreateUserDto
    {
        [Required(ErrorMessage = "Введите логин")]
        [MaxLength(User.EmailLength, ErrorMessage = "Максимальная длина логина 40 символов")]
        [RegularExpression(User.NameRegularExpression, ErrorMessage = "Логин может содержать только латинские символы, дефисы, подчеркивания, точки")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Введите Email")]
        [MaxLength(User.EmailLength, ErrorMessage = "Максимальная длина адреса электронной почты 100 символов")]
        [RegularExpression(User.EmailRegularExpression, ErrorMessage = "Введите корректный адрес электронной почты")]
        public virtual string Email { get; set; }

        [Required(ErrorMessage = "Введите имя пользователя")]
        [MaxLength(User.FullNameLength, ErrorMessage = "Максимальная длина имени пользователя 100 символов")]
        [RegularExpression(User.NameRegularExpression, ErrorMessage = "Имя пользователя может содержать только латинские символы, дефисы, подчеркивания, точки")]
        public virtual string FullName { get; set; }

        public virtual int Role { get; set; }

        [RegularExpression(User.PhoneRegularExpression, ErrorMessage = "Введите корректный номер телефона")]
        public virtual string Phone { get; set; }

        public virtual int Status { get; set; }

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

还有这个表格

@model Argussoft.BI.DAL.DTOs.UserDTOs.CreateUserDto

@using (Ajax.BeginForm("CreateUser", "User", new AjaxOptions { OnSuccess = "onSuccessCreateUser" }, new { id = "dialog_form", @class = "form-horizontal" }))
{
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4>Добавить пользователя</h4>
    </div>
    <div class="modal-body">

        <!-- Name -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Name)">Логин</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.TextBoxFor(model => model.Name, new { @class = "span3", id = "input_name" })
                    <br />
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
            </div>
        </div>

        <!-- Email -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Email)">Email</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.TextBoxFor(model => model.Email, new { @class = "span3", id = "input_email" })
                    <br />
                    @Html.ValidationMessageFor(model => model.Email)
                </div>
            </div>
        </div>

        <!-- FullName -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.FullName)">Имя пользователя</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.TextBoxFor(model => model.FullName, new { @class = "span3", id = "input_full_name" })
                    <br />
                    @Html.ValidationMessageFor(model => model.FullName)
                </div>
            </div>
        </div>

        <!-- Role -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Role)">Роль пользователя</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.DropDownList("Role", (SelectList)ViewBag.Roles,new{id ="input_role"})
                    <br />
                    @Html.ValidationMessageFor(model => model.Role)
                </div>
            </div>
        </div>

        <!-- Phone -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Phone)">Контактный телефон</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.TextBoxFor(model => model.Phone, new { @class = "span3", id = "input_phone" })
                    <br />
                    @Html.ValidationMessageFor(model => model.Phone)
                </div>
            </div>
        </div>

        <!-- Status -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Status)">Статус пользователя</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.DropDownList("Status", (SelectList)ViewBag.UserStatuses,new{id ="input_status"})
                    <br />
                    @Html.ValidationMessageFor(model => model.Status)
                </div>
            </div>
        </div>

        <!-- Password -->
        <div class="control-group">
            <label class="control-label" for="@Html.NameFor(model => model.Password)">Пароль пользователя</label>
            <div class="controls">
                <div class="input-prepend">
                    @Html.TextBoxFor(model => model.Password, new { @class = "span3", id = "input_password" })
                    <br />
                    @Html.ValidationMessageFor(model => model.Password)
                </div>
            </div>
        </div>

    </div>
    <div class="modal-footer">
        <a href="@Url.Action("UserIndex", "User")" class="btn">Отменить</a>
        <button type="submit" id="save_button" class="btn btn-primary">Сохранить</button>
    </div>
}

用户类别:

public class User : BaseEntity 
{ 
    public const int NameLength = 40; 
    public const int PasswordMinLength = 5; 
    public const int PasswordMaxLength = 20; 
    public const int FullNameLength = 100; 
    public const int EmailLength = 100; 
    public const int PhoneLength = 40; //...
}

但我的验证仅适用于RequiredRegularExpression,不适用于MinLengthMaxLength,在这种情况下我没有收到任何错误消息。

可能是什么原因?

【问题讨论】:

  • User.EmailLength 的值是多少?
  • public class User : BaseEntity { public const int NameLength = 40; public const int PasswordMinLength = 5; public const int PasswordMaxLength = 20; public const int FullNameLength = 100; public const int EmailLength = 100; public const int PhoneLength = 40; //...}

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

MaxLength 用于实体框架在创建数据库时决定字符串值字段的大小。

来自 MSDN:

指定数组的最大长度 或属性中允许的字符串数据。

StringLength 是用于验证用户输入的数据注释。

来自 MSDN:

指定最小值和最大值 允许的字符长度 在数据字段中。

非定制

使用[String Length]

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

30 是最大长度
最小长度 = 3

自定义 StringLengthAttribute 类

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

【讨论】:

  • 在这种情况下如何设置最小值和最大值?
  • 谢谢,它有效。但是如果我需要为 MinimumLength 和 MaximumLength 设置不同的错误信息,我该怎么做呢?
  • 我尝试使用您的自定义 StringLengthAttribute 类,我没有收到编译错误,但它不再起作用并且我没有收到任何验证错误。 stackoverflow.com/questions/18307385/… 有什么问题?
  • 你可以发布你的模型/视图控制器。
  • 我在这里发布我的模型和视图控制器stackoverflow.com/questions/18307385/…
【解决方案2】:

这可以代替 MaxLength 和 MinLength

[StringLength(40, MinimumLength = 10 , ErrorMessage = "Password cannot be longer than 40 characters and less than 10 characters")]

【讨论】:

  • vb.net 语法
【解决方案3】:
    [StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
    [Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
    public string Password { get; set; }

这样保存资源

"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"

【讨论】:

    【解决方案4】:

    他们现在使用最新版本的 MVC(和 jquery 验证包)。 mvc51-release-notes#Unobtrusive

    感谢answer 指出!

    【讨论】:

      【解决方案5】:

      尝试使用此属性,例如密码最小长度:

      [StringLength(100, ErrorMessage = "Максимальная длина пароля 20 символов", MinimumLength = User.PasswordMinLength)]
      

      【讨论】:

      • 如果我需要为MinimumLength和MaximumLength设置不同的错误信息,我该怎么做?
      猜你喜欢
      • 2013-01-15
      • 1970-01-01
      • 2022-11-05
      • 2022-10-08
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2016-10-30
      相关资源
      最近更新 更多