2009-09-10 6 views

risposta

41

Docs on MSDN dice che si può utilizzare il 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

Grazie Dan - ottengo un errore e anche se non è sicuro come risolvere: 'Sistema .ComponentModel.DataAnnotations.RangeAttribute 'non contiene un costruttore che accetta gli argomenti' 0 ' qualche idea? – Davy

+1

Grazie per tutto il tuo aiuto Dan - Sembra funzionare ma non riesco a sostituire le stringhe di hardcode per qualcosa come DateTime.Now.Date.toString() Ottengo: Un argomento di attributo deve essere un'espressione costante, tipo di espressione o espressione di creazione array di un parametro di attributo type Sry - Probabilmente sto facendo qualcosa di stupido :) Davy – Davy

+1

Ho difficoltà a far funzionare questo metodo implicitamente con jquery.validate. Ho l'impressione che la validazione dell'intervallo non si traduca realmente in essa? – Dusda

45

ho fatto questo per risolvere il problema

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

Basta imbattersi in questo, e sono stupito di quanto sia semplice ma efficace! Non posso credere che abbia così pochi voti. –

+0

Come si usa questo? Un esempio per favore? – StackThis

+0

Se il nome della classe è MyDateAttribute, è sufficiente mettere [MyDate] sopra la proprietà che si desidera limitare. – MadHenchbot

9

convalida jQuery non funziona con [Range (typeof (DateTime), "date1", "date2"] - My MSDN do c è errato

+0

Anche se è possibile farlo funzionare configurando '$ .validator' - [Convalida del modello MVC per data] (https://stackoverflow.com/questions/21777412/mvc-model-validation-for-date/42036626#42036626) –

2

Ecco un'altra soluzione.

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

Il semplice creare un nuovo controller MVC chiamato ValidationController e oltre questo codice in là. La cosa bella dell'approccio "Remote" è che puoi sfruttare questo framework per gestire qualsiasi tipo di convalida in base alla tua logica personalizzata.

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

Per quei rari casi in cui si è costretti a dare una data come una stringa (quando si utilizzano gli attributi), mi raccomando usando la notazione ISO-8601. Ciò elimina qualsiasi confusione sul fatto che il 01/02/2004 sia il 2 gennaio o il 1 febbraio.

[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

Io uso questo approccio:

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

e usarlo in questo modo:

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