Sto utilizzando ASP.NET MVC con DataAnnotations. Ho creato il seguente ValidationAttribute personalizzato che funziona bene.ASP.NET MVC: aggiunta di ErrorMessage personalizzato che incorpora DisplayName in ValidationAttribute personalizzato
public class StringRangeAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public int MaxLength { get; set; }
public StringRangeAttribute(int minLength, int maxLength)
{
this.MinLength = (minLength < 0) ? 0 : minLength;
this.MaxLength = (maxLength < 0) ? 0 : maxLength;
}
public override bool IsValid(object value)
{
//null or empty is <em>not</em> invalid
string str = (string)value;
if (string.IsNullOrEmpty(str))
return true;
return (str.Length >= this.MinLength && str.Length <= this.MaxLength);
}
}
Tuttavia, il messaggio di errore visualizzato è lo standard "Il campo * non è valido". Vorrei cambiare questo per essere: "Il [DisplayName] deve essere tra [minlength] e [maxlength]", tuttavia non riesco a capire come ottenere il DisplayName o anche il nome del campo all'interno di questa classe.
Qualcuno sa?
Works! Grazie mille! – Alistair
ottimo, anche se non vedo perché è richiesto il callback nel costruttore – dice