[c#] String MinLength and MaxLength validation don't work (asp.net mvc)

I have this class

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

and this form

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

User class:

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

but my validation works only for Required and RegularExpression and doesn't work for MinLength and MaxLength and I don't get any error message in this case.

What can be a reason?

This question is related to c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

The answer is


    [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"

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

Thanks to this answer for pointing it out!


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

[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]

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")]

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?