2011-08-25 24 views
16

tengo esto en mi modo de:MVC3 validación jQuery filtro MINLENGTH no trabajar

[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameRequired")] 
[MinLength(3, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameTooShort")] 
public String Name { get; set; } 

Esto termina en:

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

¿Cómo es que MINLENGTH está siendo ignorado por el compilador? ¿Cómo puedo "activarlo"?

Respuesta

32

En lugar de utilizar MinLength de atributo utilizan este lugar:

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 

String Length MSDN

Ventaja: no hay necesidad de escribir atributo personalizado

+0

'MinLength' ahora es compatible. Ver @Josh respuesta. – Mrchief

0

Compruebe esto question. Al leer los comentarios parece que tanto minlength como maxlenght no funcionan. Por lo tanto, sugieren utilizar el atributo StringLength para maxlenght. Creo que se debe escribir un atributo personalizado para el min legth

para el atributo personalizado que puede hacer algo como esto

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

Espero que ayuda

+0

¡Tiene razón, no encontró esto antes! – YesMan85

9

lugar de pasar por la molestia de crear atributos personalizados ... ¿por qué no usar una expresión regular?

// 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!")] 
Cuestiones relacionadas