1

私は以前にasp.netmvc検証についてこれを読んだことがありますが、私が何をしたいのかについては言及していませんので、このビューモデルを持っています-

public class MyViewModel
{
        [StringLength(200, MinimumLength = 2, ErrorMessage = "Invalid Name")]
        public string Name { get; set; }
        [Required(ErrorMessage = "*")]
        public DateTime StartDate { get; set; }
        [Required(ErrorMessage = "*")]
        public DateTime EndDate { get; set; }

}

I have setup the validation and it works..but now i want to add a condition like StartDate should always be greater than the End Date..how can i add such a custom logic/validation? Instead of checking it on controller explicitly and redirecting...can asp.net mvc validation accommodate something like this?

4

2 に答える 2

2

これは私がやったことです。選択した日付が今日ではないかどうかも確認しています..誰かが同様のことをしたい場合に備えて-

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class EndDateValidationAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "End date cannot be prior to start date";

        public EndDateValidationAttribute(string startDate, string endDate)
            : base(_defaultErrorMessage)
        {
            StartDateStr = startDate;
            EndDateStr = endDate;
            ErrorMessage = _defaultErrorMessage;
        }

        public string StartDateStr { get; private set; }
        public string EndDateStr { get; private set; }

        public DateTime StartDate { get; private set; }
        public DateTime EndDate { get; private set; }

        public override bool IsValid(object value)
        {
            // This is not a required field validator, so if the value equals null return true.  
            if (value == null) return true;

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object startDate = properties.Find(StartDateStr, true /* ignoreCase */).GetValue(value);
            object endDate = properties.Find(EndDateStr, true /* ignoreCase */).GetValue(value);

            StartDate = (DateTime)startDate;
            EndDate = (DateTime)endDate;

            if (StartDate > EndDate) return false;
            else if (Convert.ToDateTime(startDate) == DateTime.Today.Date)
            {
                return false;

            }
            return true;
        }
    } 

使用方法は次のとおりです-

[EndDateValidationAttribute("StartDate", "EndDate", ErrorMessage = "Start date should be after today's date and before end date!")]
    public class CustomeDate
    {
        [DisplayName("StartDate")]
        [Required(ErrorMessage = "*")]
        public DateTime StartDate { get; set; }
        [DisplayName("EndDate")]
        [Required(ErrorMessage = "*")]
        public DateTime EndDate { get; set; }
    }
于 2010-07-13T22:47:08.847 に答える
1

これについてはよくわかりませんが、カスタム検証の例として、デフォルトの asp.net MVC アカウント コントローラーと PropertiesMustMatchAttribute を調べる価値があるかもしれません。

コードを簡単に見てみると、実行可能であるはずです。

于 2010-07-13T19:45:38.490 に答える