asp.net core系列之模型绑定和验证方法(3)

在上面2.2自定义验证中,继承了ValidationAttribute进行服务端验证,还可以结合实现IClientModelValidator接口实现客户端验证,该接口用来控制要添加哪些 data- 属性。实现接口如下所示:

/// <summary> /// 自定义验证 /// </summary> public class ClassicMovieAttribute : ValidationAttribute,IClientModelValidator { private int _year; /// <summary> /// 年份参考值 /// </summary> /// <param></param> public ClassicMovieAttribute(int year) { _year = year; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { Movie movie = (Movie)validationContext.ObjectInstance; //用户不能将 1960 年以后发行的电影的流派设置为 Classic if (movie.Genre == "Classic" && movie.ReleaseDate.Year > _year) { return new ValidationResult(GetErrorMessage()); } return ValidationResult.Success; } 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 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." 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,提示错误信息,如下所示:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdsgsw.html