MVC.NET custom validator is not working
Posted
by
IvanMushketyk
on Stack Overflow
See other posts from Stack Overflow
or by IvanMushketyk
Published on 2012-04-07T20:00:29Z
Indexed on
2012/04/07
23:29 UTC
Read the original article
Hit count: 308
asp.net-mvc
|validation
I want to write a custom validator for MVC.NET framework that checks if entered date is in the future. To do it, I wrote the following class:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class InTheFutureAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} should be date in the future";
public InTheFutureAttribute()
: base(DefaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
public override bool IsValid(object value)
{
DateTime time = (DateTime)value;
if (time < DateTime.Now)
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "wrongvalue"
};
return new[] { clientValidationRule };
}
}
and added attribute to field that I want to check.
On the View page I create input field in the following way:
<div class="editor-label-search">
@Html.LabelFor(model => model.checkIn)
</div>
<div class="editor-field-search-date">
@Html.EditorFor(model => model.checkIn)
<script type="text/javascript">
$(document).ready(function ()
{ $('#checkIn').datepicker({ showOn: 'button', buttonImage: '/Content/images/calendar.gif', duration: 0, dateFormat: 'dd/mm/yy' }); });
</script>
@Html.ValidationMessageFor(model => model.checkIn)
</div>
When I submit the form for the controller that requires model with checked attribute code in my validator is called and it returns false, but instead of displaying an error it just call my controller's action and send invalid model to it.
Am I doing something wrong? How can I fix it?
Thank you in advance.
© Stack Overflow or respective owner