面向ASP的Telerik UI。NET MVC免费下载30天试用版

验证

面向ASP的Telerik UI。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生成的。基于。NET MVC的DataAnnotation应用于Model属性的属性。Validator还为ASP隐式生成的不显眼的属性创建规则。. NET MVC中的数字和日期。

以下DataAnnotation支持以下属性:

  • 要求
  • StringLength
  • 范围
  • RegularExpression

来使用ValidatorDataAnnotation属性:

  1. 创建一个然后加入所需的DataAnnotation属性。

    公共类OrderViewModel {[HiddenInput(DisplayValue = false)]公共int OrderID {get;设置;}[必选][Display(Name = "Customer")] public string CustomerID {get;设置;} [Required] [StringLength(15)] [Display(Name = "Ship Country")] public string ShipCountry {get;设置;}[必选][取值范围(1,int。MaxValue, ErrorMessage = "Freight应该大于1")][DataType(DataType. currency)] public decimal?运费{get;设置; } [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字段到模型和实现aGreaterDateAttribute属性,该属性将检查是否选中ShippedDate值大于所选值向数据库

  1. 创建一个继承自ValidationAttributeIClientValidatable,并实施IsValidGetClientValidationRules方法。

    [AttributeUsage AttributeTargets。属性,AllowMultiple = false, Inherited = true)]公共类GreaterDateAttribute: ValidationAttribute, IClientValidatable{公共字符串alererdatefield {get;设置;} protected override ValidationResult IsValid(对象值,ValidationContext ValidationContext) {DateTime?Date = value != null ?(DateTime?)value: null;var earerdatevalue = validationContext. objectttype . getproperty (earerdatefield) . getvalue (validationContext. var)ObjectInstance, null);DateTime吗?= = null ?(日期时间?) 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{//省略为简洁[Display(Name = "订单日期")][DataType(DataType.Date)]公共DateTime?OrderDate {get;设置;} [GreaterDate(alererdatefield = "OrderDate", ErrorMessage = "发货日期应该在订单日期之后")][DataType(DataType. date)] public DateTime?ShippedDate {get;设置;}}
  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)

    }

在可编辑助手中应用自定义属性

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

 @(Html.Kendo(). grid () . name ("grid") . columns (columns => {columns。Bound(0 => 0 . orderdate);列。绑定(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.validatejquery.validate.unobtrusive脚本到项目。
  2. 将它们包含在要在其中验证用户输入的视图或布局中。
  3. 在包含脚本之后,覆盖默认值忽略设置以启用对隐藏元素的验证—例如,像DropDownList和NumericTextBox这样的帮助程序有一个隐藏的输入来保留值。

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