.NET MVC 自定义日期验证器

发布于 2024-09-16 23:28:45 字数 378 浏览 9 评论 0原文

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

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

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

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

I'll be tackling writing a custom date validation class tomorrow for a meeting app i'm working on at work that will validate if a given start or end date is A) less than the current date, or B) the start date is greater than the end date of the meeting (or vice versa).

I think this is probably a fairly common requirement. Can anyone point me in the direction of a blog post that might help me out in tackling this problem?

I'm using .net 3.5 so i can't use the new model validator api built into .NET 4. THe project i'm working on is MVC 2.

UPDATE: THe class i'm writing needs to extend the System.ComponentModel.DataAnnotations namespace. In .NET 4 there is a IValidateObject interface that you can implement, that makes this sort of thing an absolute doddle, but sadly i can't use .Net 4. How do i go about doing the same thing in .Net 3.5?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

执笔绘流年 2024-09-23 23:28:45
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 即可。这就是你所追求的?

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

and in your View Model:

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

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

In your action, just check that ModelState.IsValid. That what you're after?

宣告ˉ结束 2024-09-23 23:28:45

我知道这篇文章比较旧,但是我发现的这个解决方案要好得多。

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

即行

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

可以在这里找到更好的解决方案:
ASP .NET MVC 3 验证使用自定义 DataAnnotation 属性

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

I know this post is older, but, this solution I found is much better.

The accepted solution in this post won't work if the object has a prefix when it is part of a viewmodel.

i.e. the lines

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

A better solution can be found here:
ASP .NET MVC 3 Validation using Custom DataAnnotation Attribute:

New DateGreaterThan attribute:

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

Usage example:

[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; }
杀お生予夺 2024-09-23 23:28:45

我认为应该这样做:

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

      return start > end || end < start;
}

I think this should do it:

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

      return start > end || end < start;
}
赠我空喜 2024-09-23 23:28:45
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);
    }
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);
    }
染柒℉ 2024-09-23 23:28:45
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);

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

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文