使用annotation在.NET MVC的Model进行数据校验

本文详细介绍了MVC框架中数据注解的使用方法,包括验证属性的类型、显示名称、显示格式、是否必填、正则表达式验证、数值范围验证、字符串长度限制、绑定字段等。并通过示例代码展示了具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可用的属性如下:

Data Annotation Validator Attributes

  1. DataType

    Specify the datatype of a property

  2. DisplayName

    specify the display name for a property.

  3. DisplayFormat

    specify the display format for a property like different format for Date proerty.

  4. Required

    Specify a property as required.

  5. ReqularExpression

    validate the value of a property by specified regular expression pattern.

  6. Range

    validate the value of a property with in a specified range of values.

  7. StringLength

    specify min and max length for a string property.

  8. MaxLength

    specify max length for a string property.

  9. Bind

    specify fields to include or exclude when adding parameter or form values to model properties.

  10. ScaffoldColumn

    specify fields for hiding from editor forms.



具体的用法如下:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
 [Bind(Exclude = "EmpId")]
 public class Employee
 {
 [ScaffoldColumn(false)]
 public int EmpId { get; set; }
 
 [DisplayName("Employee Name")]
 [Required(ErrorMessage = "Employee Name is required")]
 [StringLength(100,MinimumLength=3)]
 public String EmpName { get; set; } 
 
 [Required(ErrorMessage = "Employee Address is required")] 
 [StringLength(300)]
 public string Address { get; set; } 
 
 [Required(ErrorMessage = "Salary is required")] 
 [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
 public int Salary{ get; set; } 
 
 [Required(ErrorMessage = "Please enter your email address")] 
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email address")]
 [MaxLength(50)]
 [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
 public string Email { get; set; }
 }
}


更多内容请参考:http://www.dotnet-tricks.com/Tutorial/mvc/D8I4270712-MVC-Data-Annotations-for-Model-Validation.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值