2009-11-23 13 views
5

Tengo un modelo que está utilizando DataAnnotations. Algo así comoErrorMessage se ignora en DataAnnotations DataType Attribute

public class Appointment { 
    [Required(ErrorMessage="Please enter your name")] 
    public string Name { get; set; } 

    [Required(ErrorMessage="Please enter your appointment date?")] 
    [DataType(DataType.Date, ErrorMessage="Appointment date is not a date")] 
    public DateTime AppointmentDate { get; set; } 
} 

Los atributos "Requerido" respetan el valor en ErrorMessage; es decir, si no ingreso un valor, recibiré el mensaje "por favor ingrese". Sin embargo, si ingreso una cadena en el campo DateTime, recibo un mensaje de error estándar del sistema "El valor 'blah' no es válido para AppointmentDate".

Me depuré a través del código ASP.NET MVC, y parece que en el caso de FormatException no selecciona el nombre de visualización correcto de propertyMetadata. O eso, o me falta algo descaradamente obvio:/

¿Alguien se encontró con este problema? ¿Soy yo o solo beta (estoy usando ASP.NET MVC 2 Beta)?

Respuesta

2

En el atributo MVC1 DataType no hace lo que cabría esperar, parece que tampoco en MVC2. Tu mejor opción es tener una propiedad de cadena que represente la fecha, verificar su validez allí.

Aquí hay un pequeño extracto de un proyecto (utilizando DataAnnotations y XVal):

private List<ErrorInfo> _errors; 
     private List<ErrorInfo> Errors 
     { 
      get 
      { 
       if (_errors == null) 
        _errors = new List<ErrorInfo>(); 
       return _errors; 
      } 
      //set { _errors = value; } 
     } 

private string _startDateTimeString; 

     /// <summary> 
     /// A string reprsentation of the StartDateTime, used for validation purposes in the views. 
     /// </summary> 
     /// <remarks> 
     /// If the user passes something like 45/45/80 it would be a valid mm/dd/yy format, but an invalid date, 
     /// which would cause an InvalidOperationException to be thrown by UpdateModel(). By assigning dates to string properties 
     /// we can check not only the format, but the actual validity of dates. 
     /// </remarks> 
     public string StartDateTimeString 
     { 
      get 
      { 
       return _startDateTimeString; 
      } 
      set 
      { 
       // Check whether the start date passed from the controller is a valid date. 
       DateTime startDateTime; 
       bool validStartDate = DateTime.TryParse(value, out startDateTime); 
       if (validStartDate) 
       { 
        StartDateTime = startDateTime; 
       } 
       else 
       { 
        Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time.")); 
       } 

       _startDateTimeString = value; 
      } 
     } 

     partial void OnValidate(ChangeAction action) 
     { 
      if (action != ChangeAction.Delete) 
      { 
       Errors.AddRange(DataAnnotationsValidationRunner.GetErrors(this)); 

       if (StartDateTimeString != null) 
       { 
        DateTime startDateTime; 
        if (!DateTime.TryParse(StartDateTimeString, out startDateTime)) 
        { 
         Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time.")); 
        } 
       } 

       if (Errors.Any()) 
        throw new RulesException(Errors); 
      } 
     } 
    } 

Se tiene sentido tener el cheque en los dos lugares en nuestro proyecto, pero yo sólo quiero mostrar un concepto.

1

me encontré con este problema hoy y que quería compartir otra solución ...

[Required(ErrorMessage="Please enter your appointment date?")] 
//[DataType(DataType.Date, ErrorMessage="Appointment date is not a date")] 
[Range(typeof(DateTime), "1/1/1880", "1/1/2200", ErrorMessage = "...")] 
public string AppointmentDate { get; set; } 

Usted tendrá que ajustar su código para trabajar con una cadena en lugar de una fecha y hora (presumiblemente fácil si esto es parte de su modelo de vista), pero el mensaje de error funciona como se esperaba y se garantiza que la cadena será una fecha válida (posiblemente con un tiempo).

Cuestiones relacionadas