当使用自定义[必需]属性,使用客户端验证 [英] Use Client-Side Validation when custom [required] attribute is used

查看:145
本文介绍了当使用自定义[必需]属性,使用客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个项目上,我们不使用默认的dataannotation从 System.ComponentModel.DataAnnotations 命名空间属性,但自定义属性都建立。

因此​​,我们并放置在属性 [必需] 属性,但它是建立一个自定义的。

对于服务器端验证,我们成功地覆盖了自定义的验证提供了验证,但我们坚持里边反客户端验证。

我在文档阅读,我看到,当您使用默认 [必需] 属性,这类属性是在HTML元素呈现的:

 数据-VAL-lengthmax =10数据-VAL-长度分钟=3数据-VAL-所需=是必需的CLIENTNAME场。

这是由框架,其内容一般要求属性,然后做了我presume呈现HTML属性。

我们可以做的框架呈现这些属性对于我们呢?


解决方案

  

我们可以做的框架呈现这些属性对于我们呢?


是的,有两种方式:


  1. 让您的自定义属性实施的 IClientValidatable 界面,你会实现客户端验证规则。

  2. 注册自定义 DataAnnotationsModelValidator< TAttribute> 那里TAttribute将是你的自定义验证属​​性,并在那里你会实现你的自定义客户端验证规则(这是由Microsoft实现客户端验证必需的办法>属性,这就是为什么如果你写它提炼出来,你没有得到客户端验证)自定义验证属​​性。然后,你需要使用 DataAnnotationsModelValidatorProvider.RegisterAdapter 调用自定义属性来注册您的自定义模型验证器。

on this project we do not use the default dataannotation attributes from the System.ComponentModel.DataAnnotations namespace, but custom attributes are built.

So we do place a [required] attribute on a property, but it's a custom built one.

For server side validation we managed to override the validation with a custom validation provider, but we are stuck with tthe client side validation.

As i read in the docs, i see that when you use the default [required] attribute, these kind of attributes are rendered on the html elements:

data-val-lengthmax="10" data-val-length-min="3" data-val-required="The ClientName field is required."

I presume that is done by the framework, which reads the normal required attribute, and then renders the html attributes.

Can we make the framework render these attributes for us too?

解决方案

Can we make the framework render these attributes for us too?

Yes, there are 2 possibilities:

  1. Have your custom attribute implement the IClientValidatable interface where you would implement the client validation rules.
  2. Register a custom DataAnnotationsModelValidator<TAttribute> where TAttribute will be your custom validation attribute and where you would implement your custom client side validation rules (that's the approach used by Microsoft to implement client side validation for the Required attribute and that's why if you write a custom validator attribute which derives from it you don't get client side validation). Then you need to register your custom model validator with the custom attribute using DataAnnotationsModelValidatorProvider.RegisterAdapter call.

这篇关于当使用自定义[必需]属性,使用客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆