I have this in my mode:
[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameRequired")]
[MinLength(3, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameTooShort")]
public String Name { get; set; }
This ends up in:
<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>
How come MinLength is being ignored by the compiler? How can I "turn it on"?
Instead of using MinLength
attribute use this instead:
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
String Length MSDN
Advantage: no need to write custom attribute
Instead of going through the hassle of creating custom attributes...why not use a regular expression?
// 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!")]
The latest version of ASP.Net MVC now supports MinLength and MaxLength attributes. See the official asp.net mvc page: Unobtrusive validation for MinLengthAttribute and MaxLengthAttribute
Check this question.
Reading the comments it seems that both minlength and maxlenght do not work.
So they suggest to use StringLength attribute for maxlenght. I guess you should write a custom attribute for the min legth
for the custom attribute you can do something like this
[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;
}
}
Hope it helps