I have a custom validation class to validate a date. It works server side but not client side. I can't trigger the jquery method to do the check. I think I might have something wired up incorrectly with the adaptor or validator. P.S. I can get non custom client side validation to work (ex. [required]), just not my custom validation
View Model
public class HomePageViewModel
{
[Required]
public string SearchQuery { get; set; }
[DisplayName("Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[ClassDate(ErrorMessage = "Class date must be today or later.")]
public DateTime ClassDate { get; set; }
}
Validation class.
public class ClassDateAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) // ok, just use todays date day
{
return true;
}
DateTime toValidate = (DateTime) value;
if (toValidate.Day < DateTime.Now.Day) // if they are looking for classes in the past
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
{
var classDateRule = new ModelClientValidationRule();
classDateRule.ErrorMessage = "test error message";
classDateRule.ValidationType = "classdate";
yield return classDateRule;
}
}
Javascript code.
$(function () {
$(".datefield").datepicker();
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = (month) + "/" + (day) + "/" + now.getFullYear();
$('.datefield').val(today);
$.validator.unobtrusive.adapters.addSingleVal("classdate");
$.validator.addMethod("classdate", function(value) {
if (value) {
//do something to test date here
//if date is today or later
return true;
}
return false;
});
});
This is the element from my view.
@Html.TextBoxFor(model => model.ClassDate, new { @class = "datefield form-control", @id = "ClassDate", @type = "date", name = "ClassDate" })
@Html.ValidationMessageFor(model => model.ClassDate, "", new { @class = "text-danger" })
minDate: 0,? (and why do you have@id = "ClassDate", @type = "date", name = "ClassDate"- all which are are bit pointless since thats what the helper renders anyway)