2009-09-10 3 views
38

Ist es möglich, [Range] Annotation für Daten zu verwenden?Daten Annotations Datumsbereiche

so etwas wie

[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())] 

Antwort

41

Docs on MSDN sagt, dass Sie die RangeAttribute können

[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

Dank Dan - Ich erhalte eine Fehlermeldung obwohl nicht sicher, wie zu beheben: ‚System .ComponentModel.DataAnnotations.RangeAttribute 'enthält keinen Konstruktor, der' 0 'Argumente akzeptiert eine Idee? – Davy

+1

Vielen Dank für all Ihre Hilfe Dan - Das scheint zu funktionieren, aber ich kann nicht ersetzen sie HardCharts Saiten für etwas wie DateTime.Now.Date.toString() Ich bekomme: Ein Attributargument muss ein konstanter Ausdruck sein, typeof Ausdruck oder Array-Erstellungsausdruck eines Attributparametertyps Sry - Ich mache wahrscheinlich etwas dummes :) Davy – Davy

+1

Ich habe Probleme, diese Methode implizit mit jquery.validate zu arbeiten. Ich habe den Eindruck, dass die Bereichsvalidierung nicht wirklich darauf zutrifft? – Dusda

45

Ich habe dies Ihr Problem zu beheben

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

Kommen Sie einfach, und bin erstaunt, wie einfach aber effektiv es ist! Ich kann nicht glauben, dass es so wenige Stimmen hat. –

+0

Wie verwenden Sie das? Ein Beispiel bitte? – StackThis

+0

Wenn Ihr Klassenname MyDateAttribute lautet, setzen Sie [MyDate] einfach über die Eigenschaft, die Sie einschränken möchten. – MadHenchbot

9

jQuery Validierung nicht mit [Bereich funktioniert (typeof (DateTime), "date1", "date2"] - Meine MSDN tun c ist falsch

+0

Obwohl Sie es schaffen können, indem Sie den '$ .validator' konfigurieren - [MVC-Modellvalidierung für Datum] (https://stackoverflow.com/questions/21777412/mvc-model-validation-for-date/42036626#42036626) –

2

Hier ist eine andere Lösung.

Die einfach erstellen Sie einen neuen MVC-Controller namens ValidationController und hinter diesem Code in dort. Das Schöne am "Remote" -Ansatz ist, dass Sie dieses Framework nutzen können, um jede Art von Validierungen basierend auf Ihrer eigenen Logik durchzuführen.

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

Für jene seltenen Fällen, wenn Sie ein Datum als String zu schreiben sind gezwungen, (wenn Attribute verwenden), empfehle ich die ISO-8601 Notation. Das beseitigt jede Verwirrung darüber, ob der 01/02/2004 der 2. Januar oder der 1. Februar ist.

[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

Ich benutze diesen Ansatz:

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

Und wie so verwenden:

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