MaxLength 属性不生成客户端验证属性

发布于 2024-11-26 01:29:30 字数 776 浏览 6 评论 0 原文

我对 ASP.NET MVC3 客户端验证有一个奇怪的问题。我有以下课程:

public class Instrument : BaseObject
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    [MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
    public string Name { get; set; }
}

从我的角度来看:

<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

这是我为该字段的文本框生成的 HTML:

<input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value="">

没有 MaxLengthAttribute 的迹象,但其他一切似乎都正常。

有什么想法出了什么问题吗?

I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:

public class Instrument : BaseObject
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    [MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
    public string Name { get; set; }
}

From my view:

<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

And here's the generated HTML I get for the textbox for this field:

<input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value="">

No sign of the MaxLengthAttribute, but everything else seems to be working.

Any ideas what's going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

爱你是孤单的心事 2024-12-03 01:29:30

尝试使用 [StringLength] 属性:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

这是出于验证目的。例如,如果您想在输入上设置 maxlength 属性,您可以将自定义数据注释元数据提供程序编写为 本文所示 并自定义 默认模板

Try using the [StringLength] attribute:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

作死小能手 2024-12-03 01:29:30

我只是使用了jquery的一个片段来解决这个问题。

$("input[data-val-length-max]").each(function (index, element) {
   var length = parseInt($(this).attr("data-val-length-max"));
   $(this).prop("maxlength", length);
});

选择器查找具有 data-val-length-max 属性集的所有元素。这是 StringLength 验证属性将设置的属性。

Each 循环遍历这些匹配项,并解析出该属性的值并将其分配给应已设置的 mxlength 属性。

只需将其添加到您的文档准备功能中即可。

I just used a snippet of jquery to solve this problem.

$("input[data-val-length-max]").each(function (index, element) {
   var length = parseInt($(this).attr("data-val-length-max"));
   $(this).prop("maxlength", length);
});

The selector finds all of the elements that have a data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will set.

The each loop loops through these matches and will parse out the value for this attribute and assign it to the mxlength property that should have been set.

Just add this to you document ready function and you are good to go.

泪眸﹌ 2024-12-03 01:29:30

MaxLengthAttribute 自 MVC 5.1 更新以来一直有效:更改说明

MaxLengthAttribute is working since MVC 5.1 update: change notes

顾铮苏瑾 2024-12-03 01:29:30

在MVC 4中
如果您想要输入类型文本中的最大长度?你可以 !

@Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })

In MVC 4
If you want maxlenght in input type text ? You can !

@Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })
夜无邪 2024-12-03 01:29:30

支持 @Nick-Harrison 的回答:

$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});

我想知道 parseInt() 的用途是什么?我已经将其简化为这样,没有任何问题......

$("input[data-val-length-max]").each(function (index, element) {
    element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});

我会对尼克斯的答案发表评论,但还没有足够的代表。

Props to @Nick-Harrison for his answer:

$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});

I was wondering what the parseInt() is for there? I've simplified it to this with no problems...

$("input[data-val-length-max]").each(function (index, element) {
    element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});

I would have commented on Nicks answer but don't have enough rep yet.

恋竹姑娘 2024-12-03 01:29:30

我遇到了同样的问题,我可以通过在视图模型中实现 IValidatableObject 接口来解决它。

public class RegisterViewModel : IValidatableObject
{
    /// <summary>
    /// Error message for Minimum password
    /// </summary>
    public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";

    /// <summary>
    /// Minimum acceptable password length
    /// </summary>
    public const int PasswordMinimumLength = 8;

    /// <summary>
    /// Gets or sets the password provided by the user.
    /// </summary>
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    /// <summary>
    /// Only need to validate the minimum length
    /// </summary>
    /// <param name="validationContext">ValidationContext, ignored</param>
    /// <returns>List of validation errors</returns>
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var errorList = new List<ValidationResult>();
        if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
        {
            errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
        }
        return errorList;
    }
}

Razor 中的标记是...

<div class="form-group">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
    <div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
    </div>
    @Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>

这非常有效。如果我尝试使用 [StringLength] 来代替,那么呈现的 HTML 就不正确。验证应呈现为:

<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>

使用 StringLengthAttribute,呈现的 HTML 显示为 ValidationSummary,这是不正确的。有趣的是,当验证器失败时,提交仍然被阻止!

I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.

public class RegisterViewModel : IValidatableObject
{
    /// <summary>
    /// Error message for Minimum password
    /// </summary>
    public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";

    /// <summary>
    /// Minimum acceptable password length
    /// </summary>
    public const int PasswordMinimumLength = 8;

    /// <summary>
    /// Gets or sets the password provided by the user.
    /// </summary>
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    /// <summary>
    /// Only need to validate the minimum length
    /// </summary>
    /// <param name="validationContext">ValidationContext, ignored</param>
    /// <returns>List of validation errors</returns>
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var errorList = new List<ValidationResult>();
        if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
        {
            errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
        }
        return errorList;
    }
}

The markup in the Razor is then...

<div class="form-group">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
    <div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
    </div>
    @Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>

This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:

<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>

With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!

却一份温柔 2024-12-03 01:29:30

我知道我来晚了,但我终于找到了如何注册 MaxLengthAttribute

首先我们需要一个验证器:

public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
{
    private readonly string _errorMessage;
    private readonly int _length;


    public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
    : base(metadata, context, attribute)
    {
        _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
        _length = attribute.Length;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = _errorMessage,
            ValidationType = "length"
        };

        rule.ValidationParameters["max"] = _length;
        yield return rule;
    }
}

没什么特别的。在构造函数中,我们保存属性中的一些值。在 GetClientValidationRules 中,我们设置了一条规则。 ValidationType = "length" 由框架映射到 data-val-lengthrule.ValidationParameters["max"] 用于 data-val-length-max 属性。

现在,既然您有了一个验证器,您只需在 global.asax 中注册它:

protected void Application_Start()
{
    //...

    //Register Validator
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}

瞧,它就可以工作了。

I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute.

First we need a validator:

public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
{
    private readonly string _errorMessage;
    private readonly int _length;


    public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
    : base(metadata, context, attribute)
    {
        _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
        _length = attribute.Length;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = _errorMessage,
            ValidationType = "length"
        };

        rule.ValidationParameters["max"] = _length;
        yield return rule;
    }
}

Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules we set a rule. ValidationType = "length" is mapped to data-val-length by the framework. rule.ValidationParameters["max"] is for the data-val-length-max attribute.

Now since you have a validator, you only need to register it in global.asax:

protected void Application_Start()
{
    //...

    //Register Validator
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}

Et voila, it just works.

惜醉颜 2024-12-03 01:29:30

StringLength 效果很好,我这样使用它:

[StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for 
              ProductName")]
public string ProductName { get; set; }

只需使用 RegularExpression 而不使用 StringLength:

[RegularExpression(@"^[a-zA-Z0-9'@&#.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25 
                   characters allowed for ProductName")]    
public string ProductName { get; set; }

但对我来说,上述方法在显示视图中给出了错误,原因我已经在数据库中拥有超过 25 个字符的 ProductName 字段

,所以最后我遇到了 这个< /a> 和这篇文章并尝试不使用这样的模型进行验证

 <div class="editor-field">
 @Html.TextBoxFor(model => model.ProductName, new
 {
 @class = "form-control",
 data_val = "true",
 data_val_length = "Sorry only 25 characters allowed for ProductName",
 data_val_length_max = "25",
 data_val_length_min = "1"
 })
 <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span>
 </div>

这解决了我的问题,您还可以使用 jquery 或使用 ModelState.AddModelError

希望能帮助某人。

StringLength works great, i used it this way:

[StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for 
              ProductName")]
public string ProductName { get; set; }

or Just Use RegularExpression without StringLength:

[RegularExpression(@"^[a-zA-Z0-9'@&#.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25 
                   characters allowed for ProductName")]    
public string ProductName { get; set; }

but for me above methods gave error in display view, cause i had already ProductName field in database which had more than 25 characters

so finally i came across this and this post and tried to validate without model like this:

 <div class="editor-field">
 @Html.TextBoxFor(model => model.ProductName, new
 {
 @class = "form-control",
 data_val = "true",
 data_val_length = "Sorry only 25 characters allowed for ProductName",
 data_val_length_max = "25",
 data_val_length_min = "1"
 })
 <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span>
 </div>

this solved my issue, you can also do validation manually using jquery or using ModelState.AddModelError

hope helps someone.

成熟的代价 2024-12-03 01:29:30

我对 html 文档中具有 data-val-length-max 属性的所有输入(文本区域、输入等)尝试了此操作,并且它工作正常。

$(document).ready(function () {
    $(":input[data-val-length-max]").each(function (index, element) {
        var length = parseInt($(this).attr("data-val-length-max"));
        $(this).prop("maxlength", length);
    });
});

I tried this for all the inputs in my html document(textarea,inputs,etc) that had the data-val-length-max property and it works correctly.

$(document).ready(function () {
    $(":input[data-val-length-max]").each(function (index, element) {
        var length = parseInt($(this).attr("data-val-length-max"));
        $(this).prop("maxlength", length);
    });
});
燕归巢 2024-12-03 01:29:30

这可以替换 MaxLength 和 MinLength

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

This can replace the MaxLength and the MinLength

[StringLength(40, MinimumLength = 10 , ErrorMessage = "Name cannot be longer than 40 characters and less than 10")]
独孤求败 2024-12-03 01:29:30
<input class="text-box single-line" data-val="true" data-val-required="Name is required." 
    id="Name1" name="Name" type="text" value="">

$('#Name1').keypress(function () {
    if (this.value.length >= 5) return false;
});
<input class="text-box single-line" data-val="true" data-val-required="Name is required." 
    id="Name1" name="Name" type="text" value="">

$('#Name1').keypress(function () {
    if (this.value.length >= 5) return false;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文