我在我的模式中有这个:
[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameRequired")]
[MinLength(3, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameTooShort")]
public String Name { get; set; }
最终:
<div class="editor-label">
<label for="Name">Name</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="Name is required" id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
编译器如何忽略MinLength?我怎样才能“开启”?
答案 0 :(得分:32)
而不是使用MinLength
属性而是使用它:
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
优点:无需编写自定义属性
答案 1 :(得分:9)
而不是经历创建自定义属性的麻烦......为什么不使用正则表达式?
// Minimum of 3 characters, unlimited maximum
[RegularExpression(@"^.{3,}$", ErrorMessage = "Not long enough!")]
// No minimum, maximum of 42 characters
[RegularExpression(@"^.{,42}$", ErrorMessage = "Too long!")]
// Minimum of 13 characters, maximum of 37 characters
[RegularExpression(@"^.{13,37}$", ErrorMessage = "Needs to be 13 to 37 characters yo!")]
答案 2 :(得分:6)
最新版本的ASP.Net MVC现在支持MinLength和MaxLength属性。请参阅官方asp.net mvc页面:Unobtrusive validation for MinLengthAttribute and MaxLengthAttribute
答案 3 :(得分:0)
检查question。 阅读评论似乎minlength和maxlenght都不起作用。 因此他们建议对maxlenght使用StringLength属性。我猜你应该为min legth写一个自定义属性
对于自定义属性,您可以执行类似这样的操作
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MyMinLengthAttribute : ValidationAttribute
{
public int MinValue { get; set; }
public override bool IsValid(object value)
{
return value != null && value is string && ((string)value).Length >= MinValue;
}
}
希望有所帮助