我已经创建了一个自定义验证属性:

public class FutureDateAttribute : ValidationAttribute
    {
        public override bool IsValid(object value) 
        {
            if (value == null|| (DateTime)value < DateTime.Now)
                return false;

            return true;
        }

    }

How can I get this to work on client side too with jquery?

推荐答案

Here's how to proceed:

Start by defining the custom validation attribute:

public class FutureDateAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value == null || (DateTime)value < DateTime.Now)
            return false;

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "futuredate"
        };
    }
}

Notice how it implements IClientValidatable. Next we write our model:

public class MyViewModel
{
    [FutureDate(ErrorMessage = "Should be in the future")]
    public DateTime Date { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            // intentionally put in the past
            Date = DateTime.Now.AddDays(-1)
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

最后是一个观点:

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Date)
    @Html.TextBoxFor(x => x.Date)
    @Html.ValidationMessageFor(x => x.Date)
    <input type="submit" value="OK" />
}

The last part for the magic to happen is to define the custom adapter:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    // we add a custom jquery validation method
    jQuery.validator.addMethod('greaterThan', function (value, element, params) {
        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date($(params).val());
        }
        return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val()));
    }, '');

    // and an unobtrusive adapter
    jQuery.validator.unobtrusive.adapters.add('futuredate', { }, function (options) {
        options.rules['greaterThan'] = true;
        options.messages['greaterThan'] = options.message;
    });
</script>

Jquery相关问答推荐

TinyMCE不保存区块报价

try 使用jQuery AJAX将参数传递给http Post方法时出现未知错误

退出 jquery.each 循环后

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

jQuery .append() 创建两个元素而不是一个

如何使用 jQuery 的 drop 事件上传从桌面拖动的文件?

如何使用 jQuery 获取所有 ID?

这些 jQuery 就绪函数之间有什么区别?

错误找不到 jquery-2.0.2.min.map

在 contenteditable div 中的插入符号处插入 html

调整浏览器大小时调整jqGrid的大小?

使用跨域帖子发送凭据?

scrollIntoView 是否适用于所有浏览器?

jQuery中追加的相反

调用 e.preventDefault() 后提交表单

$(document).on('click', '#id', function() {}) 与 $('#id').on('click', function(){})

使用 JQuery 激活 bootstrap 选项卡

jQuery: Select 所有具有自定义属性的元素

如何在一个元素上拥有多个数据绑定属性?

如何使用 jQuery 的 form.serialize 但排除空字段