Telerik UI for ASP。NET MVC?下载30天免费试用

验证

Telerik UI for ASP。NET MVCenables you to use client-side validation and provides hints on using the Kendo UI Validator and the default jQuery validation.

使用DataAnnotation属性

Validator基于不显眼的HTML属性创建验证规则。这些不显眼的属性是由ASP生成的。asp.net MVC的DataAnnotation应用于Model属性的属性。Validator还为ASP隐式生成的不引人注目的属性创建规则。NET MVC用于数字和日期。

以下DataAnnotation属性支持:

  • 要求
  • StringLength
  • 范围
  • RegularExpression

方法使用验证器DataAnnotation属性:

  1. 创建一个并添加所需的DataAnnotation属性。

    公共类OrderViewModel {[HiddenInput(DisplayValue = false)]公共int OrderID {get;设置;}[必选][显示(名称= "客户")]public string CustomerID {get;设置;}[必选][StringLength(15)] [Display(Name = "Ship Country")] public string ShipCountry {get;设置;}[必选][范围(1,int.]MaxValue, ErrorMessage = "运费应该大于1")][DataType(datattype . currency)]公共十进制?运费{得到;设置; } [Required] [Display(Name = "Order Date")] public DateTime? OrderDate { get; set; } }
  2. 将模型的实例传递给视图。

    public ActionResult Create() {return View(new OrderViewModel());}
  3. 在基于模型的视图中创建编辑器,并在表单上初始化Validator。

    @model OrderViewModel @using (Html.BeginForm()) {
    Order @Html。HiddenFor(model => model. orderid)
    @Html。LabelFor(model => model. customerid)
    @(Html.Kendo()。DropDownListFor(model => model. customerid) . optionlabel ("Select Customer")) @Html。验证MessageFor(model => model.CustomerID)
    @Html.LabelFor(model => model.ShipCountry)
    @Html.EditorFor(model => model.ShipCountry) @Html.ValidationMessageFor(model => model.ShipCountry)
    @Html.LabelFor(model => model.Freight)
    @Html.Kendo().NumericTextBoxFor(model => model.Freight) @Html.ValidationMessageFor(model => model.Freight)
    @Html.LabelFor(model => model.OrderDate)
    @Html.Kendo().DatePickerFor(model => model.OrderDate) @Html.ValidationMessageFor(model => model.OrderDate)

    }

实现自定义属性

要实现自定义验证属性,请包含ShippedDate字段,并实现模型GreaterDateAttribute属性,该属性将检查是否选中ShippedDate值大于所选值向数据库

  1. 创建一个继承自ValidationAttribute而且IClientValidatable,并实现IsValid而且GetClientValidationRules方法。

    [AttributeUsage AttributeTargets。Property, AllowMultiple = false, Inherited = true)]公共类GreaterDateAttribute: ValidationAttribute, IClientValidatable{公共字符串早期datefield {get;设置;} protected override ValidationResult IsValid(对象值,ValidationContext ValidationContext) {DateTime?日期=值!=空?(DateTime?)值:null;var earverdatevalue = validationContext. objecttype . getproperty (earverdatefield) . getvalue (validationContext. var)ObjectInstance, null);DateTime吗?= null ?(DateTime?) if (date.HasValue && earlierDate.HasValue && date <= earlierDate) { return new ValidationResult(ErrorMessage); } return ValidationResult.Success; } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "greaterdate" }; rule.ValidationParameters["earlierdate"] = EarlierDateField; yield return rule; } }
  2. 装饰ShippedDate属性使用新实现的属性。

    公共类OrderViewModel{//为简洁省略[显示(名称= "订单日期")][DataType(datattype .Date)] public DateTime?OrderDate {get;设置;} [GreaterDate(早期datefield = "OrderDate", ErrorMessage = "发货日期应在订单日期之后")][DataType(datattype . date)] public DateTime?装运日期{获取;设置;}}
  3. 方法实现Validator规则,该规则将处理所有输入data-val-greaterdate属性。

    @model OrderViewModel @using (Html.BeginForm()) {
    Order @Html。HiddenFor(model => model. orderid)
    @Html。LabelFor(model => model. orderdate)
    @Html。DatePickerFor(model => model. orderdate) @Html。验证MessageFor(model => model.OrderDate)
    @Html.LabelFor(model => model.ShippedDate)
    @Html.DatePickerFor(model => model.ShippedDate) @Html.ValidationMessageFor(model => model.ShippedDate)

    }

在可编辑的helper中应用自定义属性

可编辑的助手,如Grid和ListView,在内部初始化Validator。要指定自定义规则,必须扩展Validator的内置验证规则。您还可以使用这种方法在包含脚本后定义规则,并在所有视图中使用它们。

<脚本>(函数($,kendo){$。扩展(真的,kendo.ui。验证器,{规则:{greaterdate:函数(输入){if (input.is("[data-val-greaterdate]") && input.val() != "") {var date = kendo. parsedate (input.val()),早期日期= kendo. parsedate。parseDate($(“[name = " + input.attr(“data-val-greaterdate-earlierdate ") + "']"). 瓦尔());返回!date || !}返回true;}},消息:{greaterdate:函数(输入){返回input.attr("data-val-greaterdate");}}});}) (jQuery,剑道); @(Html.Kendo(). grid () . name ("grid") . columns (columns => {columns. column . name)。绑定(o => o. orderdate);列。绑定(o => o. shippeddate); columns.Command(command => command.Edit()); }) .DataSource(source => source .Ajax() .Model(model => model.Id(o => o.OrderID)) .Read("Read", "Orders") .Update("Update", "Orders") ) )

使用jQuery验证

  1. 控件的最新版本jquery.validate而且jquery.validate.unobtrusive项目的脚本。
  2. 将它们包含在要验证用户输入的视图或布局中。
  3. 在包含脚本之后,重写默认值忽略设置来启用隐藏元素的验证——例如,像DropDownList和NumericTextBox这样的助手有一个隐藏的输入来保存值。

    < script src = " .content(“~ /脚本/ jquery.validate.min.js”)">