Czy można stosować adnotację [Range]
dla dat?Zakres dat danych
coś
[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]
Czy można stosować adnotację [Range]
dla dat?Zakres dat danych
coś
[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]
Docs on MSDN mówi można użyć 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;}
Zrobiłem to, aby rozwiązać problem
public class DateAttribute : RangeAttribute
{
public DateAttribute()
: base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(), DateTime.Now.AddYears(2).ToShortDateString()) { }
}
Po prostu napotkasz to i jestem zaskoczony, jak proste, ale skuteczne! Nie mogę uwierzyć, że ma tak mało głosów. –
Jak tego używasz? Przykład proszę? – StackThis
Jeśli nazwa twojej klasy to MyDateAttribute, po prostu umieść [MojaData] nad właściwością, którą chcesz ograniczyć. – MadHenchbot
walidacji jQuery nie działa [zakres (typeof (DateTime), "date1", "date2"] - Moje MSDN do c jest nieprawidłowe
Chociaż możesz sprawić, żeby działało, konfigurując '$ .validator' - [Sprawdzanie poprawności modelu MVC] (https://stackoverflow.com/questions/21777412/mvc-model-validation-for-date/42036626#42036626) –
Oto inne rozwiązanie.
[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; }
Po prostu stwórz nowy kontroler MVC o nazwie ValidationController i przejdź obok tego kodu. Zaletą podejścia "Remote" jest możliwość wykorzystania tego mechanizmu do obsługi wszelkich zatwierdzeń opartych na niestandardowej logice.
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);
}
}
}
}
Dla tych rzadkich przypadków, gdy jesteś zmuszony napisać datę jako ciąg (przy użyciu atrybutów), bardzo polecam przy użyciu notacji ISO-8601. To eliminuje jakiekolwiek zamieszanie co do tego, czy 01/02/2004 jest 2 stycznia lub 1 lutego.
[Range(typeof(DateTime), "2004-12-01", "2004-12-31",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}
Używam tego podejścia:
[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);
}
i używać go tak:
[DateRange("2004-12-01", "2004-12-2", "yyyy-M-d")]
ErrorMessage = "Value for {0} must be between {1} and {2}")]
Thanks Dan - pojawia się błąd i choć nie wiem, jak to naprawić: „System .ComponentModel.DataAnnotations.RangeAttribute "nie zawiera konstruktora, który przyjmuje argumenty" 0 " jakiś pomysł? – Davy
Dzięki za całą pomoc Dan - To wydaje się działać, ale nie mogę zastąpić tych łańcuchów hardcodes czymś takim jak DateTime.Now.Date.toString() Otrzymuję: Argument atrybutu musi być wyrażeniem stałym, wyrażeniem typeof lub wyrażenie tworzenia tablicy o parametrze typu atrybutu Sry - prawdopodobnie robię coś głupiego :) Davy – Davy
Mam problem z tym, aby ta metoda działała niejawnie przy pomocy jquery.validate. Odnoszę wrażenie, że walidacja zasięgu nie przekłada się na to? – Dusda