Вот моя проверка на стороне клиента
(function ($) {
// Here I will add code for client side validation for our custom validation (age range validation)
$.validator.unobtrusive.adapters.add("minimumage", ["minage"], function (options) {
options.rules["minimumage"] = options.params;
options.messages["minimumage"] = options.message;
});
$.validator.addMethod("minimumage", function (value, elements, params) {
if (value) {
var valDate = new Date(value);
if ((new Date().getFullYear() - valDate.getFullYear()) < parseInt(params.minage)
) {
return false;
//validation failed
}
}
return true;
});
})(jQuery);
Model.cs
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "BirthdayMandatory")]
[Display(Name = "Birthday", ResourceType = typeof(Resources.Resources))]
[MinimumAge(MinAge = 16, ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "MinimumAgeMessage")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birthday { get; set; }
Page.cshtml
<div class="form-group">
@Html.LabelFor(model => model.Birthday, new { @class = "control-label" })
@Html.TextBoxFor(model => model.Birthday, "{0:dd/MM/yyyy}", new { @class = "form-control", @name = "date", placeholder = "dd/mm/yyyy" })
@Html.ValidationMessageFor(model => model.Birthday)
</div>
Вот это MinimumAgeAttribute
:
public class MinimumAgeAttribute : ValidationAttribute, IClientValidatable
{
public int MinAge { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//THIS IS FOR SERVER SIDE VALIDATION
// if value not supplied then no error return
if (value == null)
{
return null;
}
int age = 0;
age = DateTime.Now.Year - Convert.ToDateTime(value).Year;
if (age >= MinAge)
{
return null; // Validation success
}
else
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
// error
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
//THIS IS FOR SET VALIDATION RULES CLIENT SIDE
var rule = new ModelClientValidationRule()
{
ValidationType = "minimumage",
ErrorMessage = FormatErrorMessage(metadata.DisplayName)
};
rule.ValidationParameters["minage"] = MinAge;
yield return rule;
}
}
Тогда при проверке ошибки всегда отображается ошибка Birthday must be a date
при вводе даты выше 12. Например. 20/02/1991
Я исправил это так:
//to correct dd/mm/yyyy bug in asp validation
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD/MM/YYYY", true).isValid();
}
});
Но проверка минимального возраста становится неработоспособной.
Пожалуйста, помогите