I would like to implement client-side validation in ASP.NET MVC 4. After implementing the IClientValidatable interface and adding the adapter and client validation code, the validation is still not working. Please see the code below: Custom Validation Attribute:
namespace MvcApplication1.Models
{
[AttributeUsage(AttributeTargets.Property)]
public class DateLessThanCurrentAttribute:ValidationAttribute,IClientValidatable
{
public DateLessThanCurrentAttribute(string errorMessage)
:base(errorMessage)
{ }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
if((DateTime)value>=DateTime.Now)
{
validationResult = new ValidationResult(FormatErrorMessage(base.ErrorMessage));
}
return validationResult;
}
#region IClientValidatable Implementation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string errorMessage = base.ErrorMessage;
ModelClientValidationRule dateLessthanCurrentValidationRule = new ModelClientValidationRule();
dateLessthanCurrentValidationRule.ErrorMessage = FormatErrorMessage(errorMessage);
dateLessthanCurrentValidationRule.ValidationType = "datelessthancurrent";
yield return dateLessthanCurrentValidationRule;
}
#endregion
}
}
Razor View:
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/Custom/CustomValidation.js"></script>
}
Adapter and Validator:
/// <reference path="jquery.validate.js"/>
/// <reference path="jquery.validate.unobtrusive.js"/>
$.validator.unobtrusive.adapters.addBool("datelessthancurrent");
$.validator.addMethod("datelessthancurrent", function (value, element,params) {
alert('hey you!!!');
return false;
});
Oh, i found the problem. The redundant lines below were the cause. Removing these lines solves the problem.