문제

사용이 가능한가요? [Range] 날짜에 대한 주석?

같은 것

[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]
도움이 되었습니까?

해결책

MSDN의 문서 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;}

다른 팁

나는 당신의 문제를 해결하기 위해 이것을했습니다

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

jQuery 유효성 검사는 [range (typeof (dateTime), "date1", "date2"]에서 작동하지 않습니다.

또 다른 해결책이 있습니다.

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

ValidationController라는 새 MVC 컨트롤러를 만들고 거기에 이 코드를 붙여 넣기만 하면 됩니다."원격" 접근 방식의 좋은 점은 이 프레임워크를 활용하여 사용자 지정 논리를 기반으로 모든 종류의 유효성 검사를 처리할 수 있다는 것입니다.

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

날짜를 문자열로 작성 해야하는 드문 경우 (속성을 사용할 때) 사용하는 것이 좋습니다. ISO-8601 표기법. 2004 년 1 월 2 일 1 월 2 일 또는 2 월 1 일인지 여부에 대한 혼란이 발생합니다.

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

나는이 접근법을 사용합니다.

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

그리고 그렇게 사용하십시오.

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

나는 문제를 발견했다 [Range(typeof(DateTime)] 주석이 있고 그것을 "Clunky"라고 묘사하면 그것이 작동하면 너무 많은 기회가 남습니다.

원격 검증은보기에서 JavaScript를 피하고 서버 측 코드 무결성을 유지하는 좋은 방법 인 것 같습니다. 개인적으로 클라이언트에게 코드를 보내서 피할 수있는 경우 실행하는 것을 좋아하지 않습니다.

@stackthis를 기본으로 사용하고 기사 MVC3의 원격 검증

모델

public class SomeDateModel
{
    public int MinYears = 18;
    public int MaxYears = 110;

    [Display(Name = "Date of birth", Prompt = "e.g. 01/01/1900")]
    [Remote(action: "ValidateDateBetweenYearsFromNow", controller: "Validation", areaReference: AreaReference.UseRoot, AdditionalFields = "MinYears,MaxYears", HttpMethod = "GET" ,ErrorMessage = "Subject must be over 18")]
    public DateTime? DOB { get; set; }
}

컨트롤러 - 루트 디렉토리에 배포되었습니다

namespace Controllers
{
    public class ValidationController : Controller
    {
        [HttpGet]
        [ActionName("ValidateDateBetweenYearsFromNow")]
        public JsonResult ValidateDateBetweenYearsFromNow_Get()
        {
            //This method expects 3 parameters, they're anonymously declared through the Request Querystring,
            //Ensure the order of params is:
            //[0] DateTime
            //[1] Int Minmum Years Ago e.g. for 18 years from today this would be 18
            //[2] int Maximum Years Ago e.g. for 100 years from today this would be 100
            var msg = string.Format("An error occured checking the Date field validity");
            try
            {
                int MinYears = int.Parse(Request.QueryString[1]);
                int MaxYears = int.Parse(Request.QueryString[2]);

                //Use (0 - x) to invert the positive int to a negative.
                var min = DateTime.Now.AddYears((0-MinYears));
                var max = DateTime.Now.AddYears((0-MaxYears));

                //reset the response error msg now all parsing and assignmenst succeeded.
                msg = string.Format("Please enter a value between {0:dd/MM/yyyy} and {1:dd/MM/yyyy}", max, min);
                var date = DateTime.Parse(Request.QueryString[0]);
                if (date > min || date < max)
                    //switch the return value here from "msg" to "false" as a bool to use the MODEL error message
                    return Json(msg, JsonRequestBehavior.AllowGet);
                else
                    return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(msg, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

그만큼 msg 변수는 HTML Helper ValidationSummary 또는 HTML Helper ValidationFor (x => x.dateTime)의 일부로 표시됩니다.

보다

원격 검증이 값을 컨트롤러로 전달하려면 파라미터 2와 3으로 전달 된 필드가보기에 존재해야한다는 점에 유의해야합니다.

    @Html.EditorFor(m => m.DOB)
    @Html.HiddenFor(m => m.MinYears)
    @Html.HiddenFor(m => m.MaxYears)
    @Html.ValidationSummary()

모델과 HTML 도우미는 모든 jQuery 작업을 수행합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top