2009-09-10 12 views

Respuesta

41

Docs on MSDN dice que usted puede utilizar el RangeAttribute

[Range(typeof(DateTime), "1/2/2004", "3/4/2004", 
     ErrorMessage = "Value for {0} must be between {1} and {2}")] 
public datetime Something { get; set;} 
+0

Gracias Dan - Me aparece un error, aunque no seguro de cómo solucionarlo: 'Sistema .ComponentModel.DataAnnotations.RangeAttribute 'no contiene un constructor que tome' 0 'argumentos alguna idea? – Davy

+1

Gracias por toda su ayuda Dan - Parece que funciona pero no puedo sustituir las cadenas de códigos rígidos por algo como DateTime.Now.Date.toString() Obtengo: Un argumento de atributo debe ser una expresión constante, tipode expresión o expresión de creación de matriz de un tipo de parámetro de atributo Sry - Probablemente estoy haciendo algo tonto :) Davy – Davy

+1

Tengo problemas para que este método funcione implícitamente con jquery.validate. Me da la impresión de que la validación de rango realmente no se traduce en eso? – Dusda

45

Hice esto para arreglar el problema

public class DateAttribute : RangeAttribute 
    { 
     public DateAttribute() 
     : base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(),  DateTime.Now.AddYears(2).ToShortDateString()) { } 
    } 
+1

¡Solo ven esto, y estoy sorprendido de lo simple pero efectivo que es! No puedo creer que tenga tan pocos votos. –

+0

¿Cómo se usa esto? Un ejemplo por favor? – StackThis

+0

Si su nombre de clase es MyDateAttribute, simplemente ponga [MyDate] sobre la propiedad que desea restringir. – MadHenchbot

9

validación jQuery no funciona con [Rango (typeof (DateTime), "date1", "date2"] - Mi MSDN do c es incorrecto

+0

A pesar de que puede hacerlo funcionar configurando el '$ .validator' - [Validación del modelo MVC para la fecha] (https://stackoverflow.com/questions/21777412/mvc-model-validation-for-date/42036626#42036626) –

2

Aquí hay otra solución.

[Required(ErrorMessage = "Date Of Birth is Required")] 
[DataType(DataType.Date, ErrorMessage ="Invalid Date Format")] 
[Remote("IsValidDateOfBirth", "Validation", HttpMethod = "POST", ErrorMessage = "Please provide a valid date of birth.")] 
[Display(Name ="Date of Birth")] 
public DateTime DOB{ get; set; } 

Simplemente cree un nuevo controlador MVC llamado ValidationController y pase este código allí. Lo bueno del enfoque "Remoto" es que puede aprovechar este marco para manejar cualquier tipo de validaciones basadas en su lógica personalizada.

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Net.Mail; 
using System.Web; 
using System.Web.Mvc; 

namespace YOURNAMESPACEHERE 
{ 
    public class ValidationController : Controller 
    { 
     [HttpPost] 
     public JsonResult IsValidDateOfBirth(string dob) 
     { 
      var min = DateTime.Now.AddYears(-21); 
      var max = DateTime.Now.AddYears(-110); 
      var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", max,min); 
      try 
      { 
       var date = DateTime.Parse(dob); 
       if(date > min || date < max) 
        return Json(msg); 
       else 
        return Json(true); 
      } 
      catch (Exception) 
      { 
       return Json(msg); 
      } 
     } 
    } 
} 
4

Para esos casos raros cuando se vea forzado a escribir una fecha como una cadena (cuando se utiliza atributos), le recomiendo el uso de la notación ISO-8601. Esto elimina cualquier confusión sobre si el 01/02/2004 es el 2 de enero o el 1 de febrero.

[Range(typeof(DateTime), "2004-12-01", "2004-12-31", 
    ErrorMessage = "Value for {0} must be between {1} and {2}")] 
public datetime Something { get; set;} 
0

utilizo este enfoque:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] 
internal sealed class DateRangeAttribute : ValidationAttribute 
{ 
    public DateTime Minimum { get; } 
    public DateTime Maximum { get; } 

    public DateRangeAttribute(string minimum = null, string maximum = null, string format = null) 
    { 
     format = format ?? @"yyyy-MM-dd'T'HH:mm:ss.FFFK"; //iso8601 

     Minimum = minimum == null ? DateTime.MinValue : DateTime.ParseExact(minimum, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None); //0 invariantculture 
     Maximum = maximum == null ? DateTime.MaxValue : DateTime.ParseExact(maximum, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None); //0 invariantculture 

     if (Minimum > Maximum) 
      throw new InvalidOperationException($"Specified max-date '{maximum}' is less than the specified min-date '{minimum}'"); 
    } 
    //0 the sole reason for employing this custom validator instead of the mere rangevalidator is that we wanted to apply invariantculture to the parsing instead of 
    // using currentculture like the range attribute does this is immensely important in order for us to be able to dodge nasty hiccups in production environments 

    public override bool IsValid(object value) 
    { 
     if (value == null) //0 null 
      return true; 

     var s = value as string; 
     if (s != null && string.IsNullOrEmpty(s)) //0 null 
      return true; 

     var min = (IComparable)Minimum; 
     var max = (IComparable)Maximum; 
     return min.CompareTo(value) <= 0 && max.CompareTo(value) >= 0; 
    } 
    //0 null values should be handled with the required attribute 

    public override string FormatErrorMessage(string name) => string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Minimum, Maximum); 
} 

y el uso que de este modo:

[DateRange("2004-12-01", "2004-12-2", "yyyy-M-d")] 
ErrorMessage = "Value for {0} must be between {1} and {2}")] 
Cuestiones relacionadas