Marvin Klein
Marvin Klein

Reputation: 1756

How to add range for DateTime validation

I have a simple input model for my blazor server side component. I want to use the build in validation for a DateTime property.

[Required]
public DateTime Date { get; set; }

How can I only accept DateTime values >= DateTime.Now?

Upvotes: 5

Views: 6796

Answers (3)

Vi100
Vi100

Reputation: 4204

You would have to create a custom validation attribute. But do it well, not as shown in the answers above...

using System;
using System.ComponentModel.DataAnnotations;

namespace YourAppNamespace
{
    public class FromNowAttribute : ValidationAttribute
    {
        public FromNowAttribute() {}

        public string GetErrorMessage() => "Date must be past now";

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var date = (DateTime)value;

            if (DateTime.Compare(date, DateTime.Now) < 0) return new ValidationResult(GetErrorMessage());
            else return ValidationResult.Success;
        }
    }
}

And then use it this way:

[Required]
[FromNow]
public DateTime Date { get; set; }

Upvotes: 9

Roman
Roman

Reputation: 12201

You can implement IValidatableObject interface:

public class MyClass: IValidatableObject 
{
    // other properties
 
    [Required]
    public DateTime Date { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (this.Date < DateTime.Now)
        {
            yield return new ValidationResult("Date is invalid/out of range");
        }

        // other validation conditions
    }
}

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

You can create a custom range attribute.

public class CustomDateAttribute : RangeAttribute
{
  public CustomDateAttribute()
    : base(typeof(DateTime),. 
            DateTime.NowToShortDateString(),
            DateTime.MaxValue.ToShortDateString()) 
  { } 
}

Upvotes: 4

Related Questions