I've Date field on my MVC UI named "startDate", the user selects date using jquery date picker. As i wanted to validate that selected date should not be 2 months past and 2 months future.
I've wrote the below code for validating 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 issue is, it goes to server for validating the date field. how can i achive same with client validation.
Thanks, -Naren
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 factor the year up by 100, thereby avoiding cross year comparison
Then on your SPAN id="x" onBlur="IsValid(this.value)">2001-01-01
Mike
Is limiting the available dates on the datepicker sufficient?
With jquery ui's datepicker this is pretty easy with the minDate and maxDate options, most others have similar functionality.
Have you tried using the standard Range validator in System.ComponentModel.DataAnnotations
attribute instead? Something like:
[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!
精彩评论