【问题标题】:.NET MVC Custom Date Validator.NET MVC 自定义日期验证器
【发布时间】:2010-08-31 23:59:02
【问题描述】:

明天我将为我正在工作的会议应用程序编写一个自定义日期验证类,该应用程序将验证给定的开始或结束日期是否 A) 小于当前日期,或 B) 开始日期大于会议的结束日期(反之亦然)。

我认为这可能是一个相当普遍的要求。谁能指出我的博客文章的方向,这可能会帮助我解决这个问题?

我使用的是 .net 3.5,所以我不能使用 .NET 4 中内置的新模型验证器 api。我正在处理的项目是 MVC 2。

更新:我正在编写的类需要扩展 System.ComponentModel.DataAnnotations 命名空间。在 .NET 4 中有一个可以实现的 IValidateObject 接口,这使得这种事情绝对是轻而易举,但遗憾的是我不能使用 .Net 4。我如何在 .Net 3.5 中做同样的事情?

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-mvc-2 data-annotations


【解决方案1】:
public sealed class DateStartAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateStart = (DateTime)value;
        // Meeting must start in the future time.
        return (dateStart > DateTime.Now);
    }
}

public sealed class DateEndAttribute : ValidationAttribute
{
    public string DateStartProperty { get; set; }
    public override bool IsValid(object value)
    {
        // Get Value of the DateStart property
        string dateStartString = HttpContext.Current.Request[DateStartProperty];
        DateTime dateEnd = (DateTime)value;
        DateTime dateStart = DateTime.Parse(dateStartString);

        // Meeting start time must be before the end time
        return dateStart < dateEnd;
    }
}

在您的视图模型中:

[DateStart]
public DateTime StartDate{ get; set; }

[DateEnd(DateStartProperty="StartDate")]
public DateTime EndDate{ get; set; }

在您的操作中,只需检查 ModelState.IsValid。这就是你所追求的?

【讨论】:

  • 在这种情况下,我如何从模型中获取 StartDate 和 EndDate 的值,因为它们都是用户输入的值?
  • 改变了我的答案。 :) 所以 StartDate 检查 DateTime.Now。 EndDate 检查用户输入的 StartDate 以确保它在开始日期之后。
  • 为什么我当前上下文中的 dateStartString 为空?
【解决方案2】:

我知道这篇文章比较老,但是,我找到的这个解决方案要好得多。

如果对象是视图模型的一部分时具有前缀,则本文中接受的解决方案将不起作用。

即线条

// Get Value of the DateStart property
string dateStartString = HttpContext.Current.Request[DateStartProperty];

可以在这里找到更好的解决方案: ASP .NET MVC 3 Validation using Custom DataAnnotation Attribute:

新的DateGreaterThan 属性:

public sealed class DateGreaterThanAttribute : ValidationAttribute
{
    private const string _defaultErrorMessage = "'{0}' must be greater than '{1}'";
    private string _basePropertyName;

    public DateGreaterThanAttribute(string basePropertyName) : base(_defaultErrorMessage)
    {
        _basePropertyName = basePropertyName;
    }

    //Override default FormatErrorMessage Method
    public override string FormatErrorMessage(string name)
    {
        return string.Format(_defaultErrorMessage, name, _basePropertyName);
    }

    //Override IsValid
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Get PropertyInfo Object
        var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);

        //Get Value of the property
        var startDate = (DateTime)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);

        var thisDate = (DateTime)value;

        //Actual comparision
        if (thisDate <= startDate)
        {
            var message = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(message);
        }

        //Default return - This means there were no validation error
        return null;
    }
}

使用示例:

[Required]
[DataType(DataType.DateTime)]
[Display(Name = "StartDate")]
public DateTime StartDate { get; set; }

[Required]
[DataType(DataType.DateTime)]
[Display(Name = "EndDate")]
[DateGreaterThanAttribute("StartDate")]
public DateTime EndDate { get; set; }

【讨论】:

【解决方案3】:

我认为应该这样做:

public boolean MeetingIsValid( DateTime start, DateTime end )
{
      if( start < DateTime.Now || end < DateTime.Now )
          return false;

      return start > end || end < start;
}

【讨论】:

  • 您好,谢谢,阅读您的回答后,我意识到我需要提供我的信息。当然,您提供的代码将验证日期,但这不是我遇到的问题的一部分。我需要知道要实现哪些接口来扩展 dataannotations 命名空间。还是谢谢。
【解决方案4】:
public ActionResult Index(vmemployee vme)

    {

        emplyee emp = new emplyee();
        vme.cities = new List<city>();

        vme.countries = new List<country>();

        vme.departments = new List<department>();

        Hrcontext context = new Hrcontext();
        vme.countries = context.cntentity.ToList();
        vme.cities = context.cityentity.ToList();
        vme.departments = context.deptentity.ToList();

        return View("employeelist", vme);
    }

    public ActionResult Index1(vmemployee vm)
    {

        vm.liemp = new List<emplyee>();
        return View("Searchemployee", vm);

    }
    [submit(Name = "sav")]
    public ActionResult save(vmemployee vme)
    {
        vme.cities = new List<city>();
        vme.countries = new List<country>();
        vme.departments = new List<department>();



        Hrcontext context = new Hrcontext();
        vme.countries = context.cntentity.ToList();
        vme.cities = context.cityentity.ToList();
        vme.departments = context.deptentity.ToList();
        vme.emp.Imagefile.SaveAs(@"C:\inetpub\wwwroot\hrsestem\hrsestem\images\" + vme.emp.Imagefile.FileName);
        vme.emp.Imagepath= (@"C:\inetpub\wwwroot\hrsestem\hrsestem\images\" + vme.emp.Imagefile.FileName);

        if (ModelState.IsValid == true)
        {
            context.empentity.Add(vme.emp);
            context.SaveChanges();
        }
        return View("employeelist", vme);
    }

【讨论】:

    【解决方案5】:
    public ActionResult Index()
        {
            
            return View("department1");
        }
        public ActionResult Savedata(Vmdepartment vm)
        {
    
            Hrcontext context = new Hrcontext();
            context.deptentity.Add(vm.dept);
            context.SaveChanges();
    
            return View("department1", vm);
        }
        public ActionResult Index1(Vmdepartment vm)
        {
            vm.liDepartment = new List<department>();
            
            return View("departmentview",vm);
        }
    
        public ActionResult search(Vmdepartment vm) {
            var n = vm.dept.name;
            vm.liDepartment = new List<department>();
            Hrcontext context = new Hrcontext();
            vm.liDepartment = context.deptentity.Where(a => a.name == n).ToList();
            return View("departmentview",vm);
    
        }
    }
    

    【讨论】:

    • 欢迎来到 Stack Overflow。没有任何解释的代码转储很少有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何比 OP 提供的更好。见How to Answer
    猜你喜欢
    • 1970-01-01
    • 2011-10-24
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多