2009-09-10 39 views

Trả lời

41

Docs on MSDN nói rằng bạn có thể sử dụng 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

Cảm ơn Dan - Tôi nhận được một lỗi dù và không chắc chắn làm thế nào để khắc phục: 'Hệ thống .ComponentModel.DataAnnotations.RangeAttribute 'không chứa hàm tạo có các đối số' 0 ' bất kỳ ý tưởng nào? – Davy

+1

Cảm ơn tất cả sự giúp đỡ của bạn Dan - Điều đó dường như hoạt động nhưng tôi không thể thay thế chuỗi mã cứng thứ cho một thứ như DateTime.Now.Date.toString() tôi nhận được: Đối số thuộc tính phải là biểu thức liên tục, biểu thức typeof hoặc biểu thức tạo mảng của kiểu tham số thuộc tính Sry - Tôi có thể làm điều gì đó ngu ngốc :) Davy – Davy

+1

Tôi gặp khó khăn khi sử dụng phương thức này để làm việc hoàn toàn với jquery.validate. Tôi có ấn tượng rằng việc xác nhận phạm vi không thực sự dịch nó? – Dusda

45

Tôi đã làm điều này để sửa chữa vấn đề của bạn

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

Chỉ cần đi qua này, và ngạc nhiên trước cách đơn giản nhưng hiệu quả nó được! Không thể tin rằng nó có rất ít phiếu bầu. –

+0

Bạn sử dụng cái này như thế nào? Một ví dụ xin vui lòng? – StackThis

+0

Nếu tên lớp của bạn là MyDateAttribute, chỉ cần đặt [MyDate] phía trên thuộc tính bạn muốn hạn chế. – MadHenchbot

9

jQuery xác nhận không làm việc với [Range (typeof (DateTime), "date1", "date2"] - MSDN của tôi làm c không chính xác

+0

Mặc dù bạn có thể làm cho nó hoạt động bằng cách định cấu hình '$ .validator' - [xác thực mô hình MVC cho ngày] (https://stackoverflow.com/questions/21777412/mvc-model-validation-for-date/42036626#42036626) –

2

Đây là một giải pháp khác.

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

Chỉ cần tạo bộ điều khiển MVC mới có tên ValidationController và nhập mã này vào đó. Điều tốt đẹp về cách tiếp cận "Từ xa" là bạn có thể tận dụng khung công tác này để xử lý bất kỳ loại xác thực nào dựa trên logic tùy chỉnh của bạn.

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

Đối với những trường hợp hiếm khi bạn bắt buộc phải viết ngày dưới dạng chuỗi (khi sử dụng thuộc tính), tôi khuyên bạn nên sử dụng ký hiệu ISO-8601. Điều đó giúp loại bỏ bất kỳ sự nhầm lẫn nào về việc liệu ngày 01/02/2004 là ngày 2 tháng 1 hay ngày 1 tháng 2.

[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

tôi sử dụng phương pháp này:

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

Và sử dụng nó như vậy:

[DateRange("2004-12-01", "2004-12-2", "yyyy-M-d")] 
ErrorMessage = "Value for {0} must be between {1} and {2}")] 
Các vấn đề liên quan