设为首页 加入收藏

TOP

asp.net core系列 45 Web应用 模型绑定和验证(四)
2019-09-17 18:35:13 】 浏览:56
Tags:asp.net core 系列 Web 应用 模型 绑定 验证
}
private string GetErrorMessage() { return $"Classic movies must have a release year earlier than {_year}."; } public void AddValidation(ClientModelValidationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-classicmovie", GetErrorMessage()); var year = _year.ToString(CultureInfo.InvariantCulture); MergeAttribute(context.Attributes, "data-val-classicmovie-year", year); } private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } }

     生成的源html代码如下所示:

<input class="form-control" type="date" 
data-val="true" 
data-val-classicmovie="Classic movies must have a release year earlier than 1960."
data-val-classicmovie-year="1960" 
data-val-required="The ReleaseDate field is required." 
id="ReleaseDate" name="ReleaseDate" value="1989-02-12">    

     在上面虽然实现了IClientModelValidator接口,但jQuery不了解规则或消息,还需要自定义classicmovie客户端验证方法,添加到jQuery validator对象。脚本如下所示:

//添加验证方法
$.validator.addMethod('classicmovie',function (value, element, params) {
         //value ,是当前验证的元素的值。
         //element  元素本身。
         //params 是传入的参数(options.rules)
        var genre = $("#form1").find("#Genre").val(),
            year = params[0],
            date = new Date(value);
        if (genre.length > 0 && genre === 'Classic') {
            // Since this is a classic movie, invalid if release date is after given year.
            return date.getFullYear() <= year;
        }
        return true;
    });

//注册一个适配器,参数1是适配器名称,参数2是验证规则的名称
$.validator.unobtrusive.adapters.add('classicmovie',['year'],function (options) {
        //适配器规则绑定到jquery validation上面
        options.rules['classicmovie'] = [parseInt(options.params['year'])];
        options.messages['classicmovie'] = options.message;
    });

     运行程序,ReleaseDate是1989年,Genre是Classic,点击Save,客户端验证返回false,提示错误信息,如下所示:

    

  参考文献

    模型绑定

    模型验证

  

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Powershell极速教程-如何在三分钟.. 下一篇Bartender标签传参与打印

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目