Check Future Date Validation in MVC
Hi, Today I come up with a very common issue (i.e.: Check if date is Future Date) which was very easy in ASP.Net web form but in MVC it is a bit tricky.
The trick is nothing but we have to write our own validator. This process can be useful in validation of Birthdate and etc. So lets start adding a custom validator for same.
Add a usual js function to check if it is future date or not :-
jQuery.validator.addMethod("isfuturedate", function (value, element, params) {
if (value != "__/__/____" && value != "") {
var mm = value.substr(0, 2);
var dd = value.substr(2, 2);
var yyyy = value.substr(4, 4);
var fdtDate = mm + "/" + dd + "/" + yyyy;
fdtDate = Date.parse(fdtDate); // console.log(fdtDate);
var ldtCurrentDate = new Date();
if (fdtDate > ldtCurrentDate) {
return false;
}
}
return true;
});
Register the above method in jquery.validators adapter :-
jQuery.validator.unobtrusive.adapters.add("isfuturedate", function (options) {
if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "TEXT") {
options.rules["isfuturedate"] = true;
if (options.message) {
options.messages["isfuturedate"] = options.message;
}
}
});
Write same logic in your model for server side validation :-
public class NoFutureDateAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
DateTime loDate = Convert.ToDateTime(value);
if (loDate > DateTime.Now)
return false;
return true; // default true
}
// Implement IClientValidatable for client side Validation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "isfuturedate", ErrorMessage = this.ErrorMessage } };
}
}
Apply Data Annotation Attributes as below :-
[NoFutureDate(ErrorMessage = "Date cannot be greater than todays date.")]
[DisplayName("Birth Date")]
[DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public object stBirthdate { get; set; }
Validate CheckBox Must be true in Asp.Net MVC
Many times we want users to accept the terms and condition to proceed using a checkbox.
Lets learn how to validate CheckBox as required field in ASP.Net MVC. The logic is very simple.
Markups for same is written below. Add validation adapter to your custom js and write same logic in your model.
Then you can simply annotate the attribute.
Markups for CheckBox in View :-
@Html.CheckBoxFor(model => model.is_accepted)) Please accept to proceed.
@Html.ValidationMessageFor(model => model.is_accepted)
Add Custom Validator in your custom js file :-
jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {
if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
Register "MustBeTrue" Custom Validator in your Model :-
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value is bool && (bool)value;
}
// Implement IClientValidatable for client side Validation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkboxtrue", ErrorMessage = this.ErrorMessage } };
}
}
Data Annotation Attribute for same is below :-
[MustBeTrue(ErrorMessage = "This field is required.")]
public object is_accepted { get; set; }