Date validation using ASP.NET MVC 3.0

I have a Date field on my MVC UI called "startDate", the user selects the date using jquery date picker. Since I wanted to confirm that the selected date should not be 2 months and 2 months in the future.

I wrote the code below to confirm the date.

 public sealed class DateAttribute : DataTypeAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EmailAddressAttribute"/> class.
        /// </summary>
        public DateAttribute() : base(DataType.Date)
        {
        }

        /// <summary>
        /// Checks that the value of the data field is valid.
        /// </summary>
        /// <param name="value">The data field value to validate.</param>
        /// <returns>
        /// true always.
        /// </returns>
        public override bool IsValid(object value)
        {
            DateTime inputDate = Convert.ToDateTime(value, CultureInfo.CurrentCulture);

            if (inputDate.Date >= DateTime.Now.Date.AddMonths(-2) && inputDate.Date <= DateTime.Now.Date.AddMonths(2))
                return true;

            return false;
        }
    }

But the problem is that it goes to the server to check the date field. how can i achieve this with client validation.

Thanks, -Naren

+3
source share
3 answers
function IsValid(object) {  
    var theDate = new Date(object);  
    var pointfrom = (theDate.getFullYear() * 100) + (theDate.getMonth());  
    var today = new Date();  
    if (pointfrom > (today.getFullYear() * 100) + (today.getMonth()) + 2) return false;  
    if (pointfrom < (today.getFullYear() * 100) + (today.getMonth()) - 2) return false;  
    return true;  
 } 

I multiplies the year by 100, thereby avoiding comparisons between years

Then on your SPAN id = "x" onBlur = "IsValid (this.value)"> 2001-01-01

Mike

0
source

Is the restriction of the available dates on the sampling date sufficient?

jquery ui datepicker minDate maxDate, .

0

Have you tried using the standard Range validator in an attribute System.ComponentModel.DataAnnotations? Sort of:

[Range(typeof(DateTime), 
    DateTime.Now.Date.AddMonths(-2).ToShortDateString(), 
    DateTime.Now.Date.AddMonths(2).ToShortDateString(), 
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime StartDate { get; set; }

Worth a try!

-7
source

All Articles