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:
[Require
You must specify dates in a certain format on the attribute and you also much provide the value in that format as well. The date input doesn't like MM/dd/yyyy
, even though that's the format it displays in! Pretty retarded IMHO.
You need to add min and max like so:
Resulting Html
<input class="form-control text-box single-line input-validation-error" data-val="true" data-val-date="The field DOB must be a date." data-val-required="The DOB field is required." id="DOB" name="DOB" type="date" value="1932-01-01" aria-required="true" aria-describedby="DOB-error" aria-invalid="true" min="1932-01-01" max="2015-01-01">
Model
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
View
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control", min = "1900-01-01", max = "2015-01-01" } })
Then you will get min or max errors in the UI:
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; }
Checking the range date can also be done using FluentValidation, that can be another solution to your problem, check my answer her. Hope this helps
MVC model validation for date
Use DataFormat attribute for specifying the date format explicitly as,
[DisplayFormat(DataFormatString="{0:C}")]
Refer MSDN doc
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