天天看点

Using Validation Annottions 使用验证

You can use four attributes in the DataAnnotations namespace to cover common validation scenarios.

Required    特性

Like all the built-in validation attributes,the Required attribute delivers both server-side and client-side  validation logic(alothough internally,it is another component in the MVC framework that delivers the client-side validation logic for the attribute through a validation adapter design).

Required 特性是服务器端和客户端同时存在的,即使用户禁用了javascript,但是服务器的验证也是会起作用的。

2.StringLength  字符串长度

MinimumLength表示的是字符串的最小长度

3.RegularExpression 正则表达式 

4.Range 

The Range attribute specifies minimum and maximum constraints for a numerical value.The first parameter to the attribute is the minimum value,and the second parameter is the maximum value.The values are incluse(包含).就是说Range特性是包含那两个参数值的。

上面的四个验证来自System.ComponentModel.DataAnnotations  命名空间

下面介绍两个来自System.Web.Mvc命名空间中的验证特性

Remote特性  可以用来进行客户端与服务器的动态交互

服务器端会返回包含true或false的json数据

The second attribute is Compare.  这时用来比较一个输入的值是否和另外一个输入的值相同的特性。

对于每一个验证出错都会有对应的 出错信息,这个信息在所有的验证中都是可以自己定制的。并且可以进行错误信息的本地化操作。

The validation features of Asp.net MVC are part of a coordinate system involving model binders,model metadata,model validators  and model state.

By default,the asp.net MVC framework executes validation logic during model binding.MVC框架执行数据验证是在Model Binding 即 数据绑定的时候。或者说是模型绑定的时候。

The model binder catches all the failed validation rules and places them into model state.

Model  State  模型状态 是个值得研究的东西,因为他包含了错误信息,以及出现错误的值

ModelState.IsValid 表示当前有效

可以自己定义需要的验证特性,只需要让他继承自ValidationAttribute特性即可在任何你想使用的地方使用该特性进行验证。

Display Attribute  

The Display attribute sets the friendly “display name”   for a model property.You can use the Display attribute to fix the label for the FirstName field.

ScaffordColumn  

The ScaffoldColumn attribute hides a property from HTML helpers such as EditorForModel and DisplayForModel.

DisplayFormat  表示的是对数值的格式化操作  要使该特性有效,必须使ApplyFormatInEditModel有效

DataType 表示的数值的类型 例如:[DataType(DataType.Password)]  表示一个密码

UIHint attribute

The UIHint attribute gives the asp.net MVC runtime the name of template to use when rendering output with the template helpers(like DisplayFor  and EditorFor).You can define your own template helpers to override the default MVC behavior.

HiddenInput  attribute

The HiddenInput attribute lives in the System.Web.Mvc namespace and tells the runtime to render an input element with a type of ‘hidden’.

以上这些就是在Model验证中的特性类,以后我会逐个的分析每个特性的用处。

我又回来了,回到了技术最前线,

继续阅读