Thomas
Thomas

Reputation: 34188

How to validate date in my model at client side with data annotation

i have 2 specific require for date validation. 1) date field should be mandatory 2) invalid date will not be accepted.

when date will be empty then i want to show "Date is required"

when date will be invalid then i want to show "Date is invalid"

so guide me how could i do this.

here i try to wrote a code but do not know does it work or not.

public class Student
    {
        [Required(ErrorMessage = "DOB require")]
        [Display(Name = "DOB :")]
        [DataType(DataType.Date)]
        public DateTime Dob { get; set; }

    }

help me to implement this at client side. thanks

EDIT

one person guide me in this way Inorder to validate date format, its better to create a custom ValidationAttribute as shown below

[AttributeUsage(AttributeTargets.Property, Inherited = false,
    AllowMultiple = false)]
public sealed class DateOnlyAttribute : ValidationAttribute
{
    public DateOnlyAttribute() :
        base("\"{0}\" must be a date without time portion.")
    {
    }

    public override bool IsValid(object value)
    {
        if (value != null)
        {
            if (value.GetType() == typeof(DateTime))
            {
                DateTime dateTime = (DateTime)value;
                return dateTime.TimeOfDay == TimeSpan.Zero;
            }
            else if (value.GetType() == typeof(Nullable<DateTime>))
            {
                DateTime? dateTime = (DateTime?)value;
                return !dateTime.HasValue
                    || dateTime.Value.TimeOfDay == TimeSpan.Zero;
            }
        }
        return true;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentCulture,
            ErrorMessageString, name);
    }
}

And then you can use it as data annotation as shown below

  [DateOnly]
public DateTime Dob { get; set; }

but the above code is not clear to me because i am new in MVC

here is few question on the above code

this code is not clear

public override bool IsValid(object value)
    {
        if (value != null)
        {
            if (value.GetType() == typeof(DateTime))
            {
                DateTime dateTime = (DateTime)value;
                return dateTime.TimeOfDay == TimeSpan.Zero;
            }
            else if (value.GetType() == typeof(Nullable<DateTime>))
            {
                DateTime? dateTime = (DateTime?)value;
                return !dateTime.HasValue
                    || dateTime.Value.TimeOfDay == TimeSpan.Zero;
            }
        }
        return true;
    }

1) when this is true then what will be return

if (value.GetType() == typeof(DateTime))

2) what this line will do

return dateTime.TimeOfDay == TimeSpan.Zero;

3) what is the meaning of this line

else if (value.GetType() == typeof(Nullable))

4) what is the meaning of this below code

DateTime? dateTime = (DateTime?)value;
                return !dateTime.HasValue
                    || dateTime.Value.TimeOfDay == TimeSpan.Zero;

please guide me in detail to understand the code what u have written. thanks

Upvotes: 0

Views: 1643

Answers (1)

AthibaN
AthibaN

Reputation: 2087

Include the following code in the .cshtml file in which you need the client side validation,

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

EDIT

The explanation for the last 4 questions you have asked,

1) if (value.GetType() == typeof(DateTime)) Checks the type of 'value'(object) can be DateTime or not ! In other word, it checks for non nullable date format.

2) return dateTime.TimeOfDay == TimeSpan.Zero; returns false if 'value' has a valid date TimeSpan.Zero returns TimeSpan for Zero Time (00:00:00) Note: if you cannot cast 'value' to date time, you get 'datetime' value equal to TimeSpan.Zero

3) else if (value.GetType() == typeof(Nullable)<DateTime>) Same case a question 1, but checking for nullable DateTime (Note: Nullable DateTime and non nullable DateTime are treated as different datatype)

4)

    DateTime? dateTime = (DateTime?)value;
    return !dateTime.HasValue || dateTime.Value.TimeOfDay == TimeSpan.Zero;

Same case as question 2, if you cannot cast to nullable DateTime, you have 'datetime' equal to TimeSpan.Zero

Upvotes: 1

Related Questions