20

I have the following code:

        [DisplayName("58.Date and hour of birth")]
        [DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy hh:mm")]
        [Range(typeof(DateTime), "1/1/2011", "1/1/2016")]
        [RequiredToClose]
        public object V_58 { get; set; }

I want to force the inclusion of time (in format hh:mm) and not only the date. This code considers 1/1/2011 as valid when it shouldn't as it does not containt the hour , Any clue about how to express the correct format ? (dd/mm/yyyy hh:mm)

Peter Kelly
  • 14,253
  • 6
  • 54
  • 63
Marc
  • 2,023
  • 4
  • 16
  • 30

5 Answers5

31

You could write your own ValidationAttribute and decorate the property with it. You override the IsValid method with your own logic.

public class MyAwesomeDateValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dt;
        bool parsed = DateTime.TryParse((string)value, out dt);
        if(!parsed)
            return false;

        // eliminate other invalid values, etc
        // if contains valid hour for your business logic, etc

        return true;
    }
}

And finally, decorate your property:

[MyAwesomeDateValidation(ErrorMessage="You were born in another dimension")]
public object V_58 { get; set; }

Note: Be wary of multiple validation attributes on your properties, as the order in which they are evaluated is unable to be determined without more customization, and subsequently if validation logic overlaps, your error messages might not accurately describe what exactly you mean to be wrong with the property (yeah, that's a run-on sentence)

matt_lethargic
  • 2,706
  • 1
  • 18
  • 33
David Fox
  • 10,603
  • 9
  • 50
  • 80
  • 2
    Keep in mind that inheriting directly from ValidationAttribute means that the built-in client-side validation will not operate, so it’s probably better to inherit from RegularExpressionAttribute (like @user329957 does) so that the built-in regex stuff will work automatically on the client. – Glenn Doten Mar 30 '11 at 13:04
  • IsValid needs to be public, not protected. http://msdn.microsoft.com/en-us/library/cc679289.aspx. – aknuds1 Oct 17 '12 at 11:52
4

Finally solved with a custom ValidationAttribute :

public class DateTimeValidation : RegularExpressionAttribute {
    public DateTimeValidation()
        : base(@"^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2})) (20|21|22|23|[0-1]?\d):[0-5]?\d$") {
        ErrorMessage = "Date must be in the format of : dd/mm/yyyy hh:mm";
    }
}
Marc
  • 2,023
  • 4
  • 16
  • 30
0

If you just pass date in a string it will consider it as 12:00 AM. If you want to pass time within a string use "06/06/2011 7:00 PM" syntax.

Other workaround would be to keep your string as is, convert it to DateTime & then AddHours &/or AddMinutes to DateTime object depending on your needs.

DAK
  • 1,395
  • 4
  • 22
  • 35
0

Validation for DataTime Variable : While taking the input for the model properties these validations can be used in the set property to check whether the input is in correct format or not.

{
        set
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Kindly enter the date!");
                }
                DateTime date;
                var isValidDate = DateTime.TryParse(value, out date);
                if (isValidDate)
                    dateofpublish = value;
                else
                    throw new Exception("Invalid Date Format");
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Dateofpublish = Console.ReadLine();
            }
        }
        get { return dateofpublish; }
    }
Sanskar7_8
  • 11
  • 2
0

This solution doesn't allow to input time 00.00, but will work with another values.

public class TimeRequiredAttribute : ValidationAttribute
{
    protected override IsValid(object value)
    {
        DateTime result;
        bool parsed = DateTime.TryParse((string)value, out result);
        if(!parsed && DateTime.MinValue.TimeOfDay == result.TimeOfDay)
        {
           return false;
        }
        return true;
    }
}

But it will work only with string proprety.

Alex Shkor
  • 1,209
  • 1
  • 10
  • 18