26

選択した単一の日付が現在の日付以上である必要がある日付検証用のMVC3データ注釈を見た人はいますか?

すでにサードパーティのアドオンがある場合は、それもクールです。私はすでにDataAnnotationsExtensionsを使用していますが、探しているものが提供されていません。

これについての言及はないようです。ですから、私が車輪の再発明を試みて独自のカスタムバリデーターを作成する前に、誰かがすでにこれを解決していることを願っています。

私は試しましRangeたが、2つの日付が必要であり、両方とも文字列形式の定数である必要があります[Range(typeof(DateTime), "1/1/2011", "1/1/2016")]が、それは役に立ちません。また、DataAnnotationsExtensionsMinバリデーターはintdouble


解決済みの更新

@BuildStartedのおかげで、これは私が最終的に得たものであり、サーバー側で、そして今ではクライアント側でスクリプトを使用してうまく機能します


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Web.Models.Validation {

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class DateMustBeEqualOrGreaterThanCurrentDateValidation : ValidationAttribute, IClientValidatable {

        private const string DefaultErrorMessage = "Date selected {0} must be on or after today";

        public DateMustBeEqualOrGreaterThanCurrentDateValidation()
            : base(DefaultErrorMessage) {
        }

        public override string FormatErrorMessage(string name) {
            return string.Format(DefaultErrorMessage, name);
        }  

        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
            var dateEntered = (DateTime)value;
            if (dateEntered < DateTime.Today) {
                var message = FormatErrorMessage(dateEntered.ToShortDateString());
                return new ValidationResult(message);
            }
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            var rule = new ModelClientCustomDateValidationRule(FormatErrorMessage(metadata.DisplayName));
            yield return rule;
       }
    }

    public sealed class ModelClientCustomDateValidationRule : ModelClientValidationRule {

        public ModelClientCustomDateValidationRule(string errorMessage) {
            ErrorMessage = errorMessage;
            ValidationType = "datemustbeequalorgreaterthancurrentdate";
        }
    }
}

そして私のモデルでは

[Required]
[DateMustBeEqualOrGreaterThanCurrentDate]
public DateTime SomeDate { get; set; }

クライアント側のスクリプト

/// <reference path="jquery-1.7.2.js" />

jQuery.validator.addMethod("datemustbeequalorgreaterthancurrentdate", function (value, element, param) {
    var someDate = $("#SomeDate").val();
    var today;
    var currentDate = new Date();
    var year = currentDate.getYear();
    var month = currentDate.getMonth() + 1;  // added +1 because javascript counts month from 0
    var day = currentDate.getDate();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();

    today = month + '/' + day + '/' + year + '  ' + hours + '.' + minutes + '.' + seconds;

    if (someDate < today) {
        return false;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("datemustbeequalorgreaterthancurrentdate");
4

3 に答える 3

22

カスタム属性を作成します。

public class CheckDateRangeAttribute: ValidationAttribute {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        DateTime dt = (DateTime)value;
        if (dt >= DateTime.UtcNow) {
            return ValidationResult.Success;
        }

        return new ValidationResult(ErrorMessage ?? "Make sure your date is >= than today");
    }

}

コードはカフから書き出されたので、エラーを修正してください:)

于 2012-06-04T20:34:11.977 に答える
12

[Remote]シンプルで簡単な特別な検証に使用します。

あなたのモデル:

[Remote("ValidateDateEqualOrGreater", HttpMethod="Post", 
    ErrorMessage = "Date isn't equal or greater than current date.")]
public DateTime Date { get; set; }
//other properties

あなたの行動:

[HttpPost]
public ActionResult ValidateDateEqualOrGreater(DateTime Date)
{
     // validate your date here and return True if validated
     if(Date >= DateTime.Now)
     {
       return Json(true);
     }
     return Json(false);    
}
于 2012-06-04T20:37:15.863 に答える
-6

このタスクを実行する簡単な方法は、を使用することCompareValidatorです。

以下のコードは、AjaxControlToolKitのを使用していますCalendarExtender。以下のコードをHTMLディレクティブにコピーします

<asp:TextBox ID="txtCompletionDate" runat="server" CssClass="txtNormal"></asp:TextBox>
                        <cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtCompletionDate"
                            Format="dd/MM/yyyy" runat="server">
                        </cc1:CalendarExtender>
                        <asp:RequiredFieldValidator ID="rfvCompletionDate" runat="server" ControlToValidate="txtCompletionDate"
                            CssClass="labelError" ErrorMessage="*"></asp:RequiredFieldValidator>
                        <asp:CompareValidator ID="cvDate" runat="server" ControlToCompare="hiddenbox" ErrorMessage="*"
                            ControlToValidate="txtCompletionDate" CssClass="labelError" ToolTip="Completion  Date should be greater than or equal to Today"
                            Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>                        
                        <asp:TextBox ID="hiddenbox" runat="server" CssClass="hiddenbox">
</asp:TextBox>

CSSに以下の行を追加します

.hiddenbox {display:none;}
于 2012-07-08T09:02:17.253 に答える