I want to check an Datetime field in a form. The field is valid between 01/10/2008 and 01/12/2008. Here is how I defined the viewmodel property:
[Required(ErrorMessage = "The date value is mandatory")]
[DataType(DataType.DateTime)]
[Range(typeof(DateTime), "01/10/2008", "01/12/2008")]
[DisplayName("When the work starts")]
public DateTime StartWork { get; set; }
I want to validate this on the client side. But I get always an error. I give the value 01/11/2008 and it tells me, that the date must be defined between 01/10/2008 and 01/12/2008. I read that it doesn't work client validation without jquery, isn't it? Or I forgot anything? What alternatives are there to get any solution of that problem.
We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.
The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.
Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5. Web API controllers don't have to check ModelState. IsValid if they have the [ApiController] attribute.
I think you can implement this using custom validation in MVC. Try using this:
[ValidateDateRange]
public DateTime StartWork { get; set; }
Here is your custom validation implementation:
namespace MVCApplication
{
public class ValidateDateRange: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// your validation logic
if (value >= Convert.ToDateTime("01/10/2008") && value <= Convert.ToDateTime("01/12/2008") )
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Date is not in given range.");
}
}
}
}
UPDATE:
You can also pass date ranges as parameters to make the validation a generic one:
[ValidateDateRange(FirstDate = Convert.ToDateTime("01/10/2008"), SecondDate = Convert.ToDateTime("01/12/2008"))]
public DateTime StartWork { get; set; }
Custom Validation:
namespace MVCApplication
{
public class ValidateDateRange: ValidationAttribute
{
public DateTime FirstDate { get; set; }
public DateTime SecondDate { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// your validation logic
if (value >= FirstDate && value <= SecondDate)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Date is not in given range.");
}
}
}
}
UPDATE 2: (For Client Side) A very simple jQuery logic should do the client validation. Check below:
$(document).ready(function(){
$("#btnSubmit").click(function(){
var dt = $("#StartWork").val();
var d = new Date(dt);
var firstDate = new Date("2008-01-10");
var secondDate = new Date("2008-01-12");
if(d>= firstDate && d<= secondDate)
{
alert("Success");
}
else
{
alert("Date is not in given range.");
}
});
});
Please check this JSFiddle to see the working demo:Date Range Validation
Though portions of this have been posted before and downvoted as not working. I can confirm this does work as long as you have both the range and the format string specified.
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:mm-dd-yyyy}", ApplyFormatInEditMode = true)]
[Range(typeof(DateTime), "1/1/1900", "12/31/2018",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With