最大属性不生成客户端验证属性
-
22-10-2019 - |
题
我对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
, ,但是其他一切似乎都在起作用。
有什么想法出了什么问题?
其他提示
我只是使用jQuery片段来解决这个问题。
$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});
选择器找到具有数据val-Length-Max属性集的所有元素。这是StringLength验证属性将设置的属性。
每个循环循环通过这些匹配,并将解析此属性的值,并将其分配给应该设置的MXLENGTH属性。
只需将其添加到您的文档“就绪功能”中,就可以了。
MaxLengthAttribute
自MVC 5.1更新以来正在工作: 更改笔记
在MVC 4中,如果您想要输入类型文本中的Maxlenght?你可以 !
@Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })
向 @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"))
});
我本可以评论尼克的答案,但还没有足够的代表。
我遇到了同样的问题,并且能够通过在视图模型中实现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;
}
}
然后,剃须刀中的标记是...
<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>
使用StringLengthTribute渲染的HTML显示为不正确的验证符号。有趣的是,当验证器失败时,提交仍然被阻止!
StringLength
效果很好,我以这种方式使用它:
[StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for
ProductName")]
public string ProductName { get; set; }
或者 只是使用 RegularExpression
没有字符串长度:
[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字段
所以我终于遇到了 这个 和 这个 张贴并试图 验证没有这样的模型:
<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
希望帮助某人。
我知道我参加聚会很晚,但是我最终发现了我们如何注册 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-length
通过框架。 rule.ValidationParameters["max"]
是为了 data-val-length-max
属性。
现在,由于您有验证器,您只需要在 global.asax
:
protected void Application_Start()
{
//...
//Register Validator
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}
eto voila,它只是有效的。
我对具有数据val-max属性的HTML文档(TextArea,Inputs等)中的所有输入进行了尝试,并且可以正常工作。
$(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);
});
});
这可以替换最大长度和最小长度
[StringLength(40, MinimumLength = 10 , ErrorMessage = "Name cannot be longer than 40 characters and less than 10")]
<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;
});