博客
关于我
ASP.NET MVC3中Model验证
阅读量:787 次
发布时间:2019-03-24

本文共 2144 字,大约阅读时间需要 7 分钟。

在开发过程中,为了确保数据在传递过程中的有效性,我们需要对数据模型中的各个字段进行验证。微软的 System.ComponentModel.DataAnnotations 命名空间提供了一系列特性,可以用来对数据模型中的字段进行验证。这些特性可以用于定义常见的验证规则,例如范围检查和必填字段,并且可以通过 DataAnnotations 提供客户端和服务器端的验证检查,减少了对数据有效性的手动编码需求。

1. 非空验证

为了确保字段不为空,我们可以使用 [Required(ErrorMessage = "字段不能为空")] 特性。

[DisplayName("姓名")]
[Required(ErrorMessage = "姓名不能为空")]
public string Name { get; set; }

2. 字符长度验证

为了控制字段的字符长度,可以使用 [StringLength(n, ErrorMessage = "错误信息")] 特性。

[DisplayName("密码")]
[StringLength(6, ErrorMessage = "密码不能超过6个字符")]
public string Password { get; set; }

3. 数字验证

为了确保字段是有效的数字,可以使用 [Range(minValue, maxValue, ErrorMessage = "错误信息")] 特性。

[DisplayName("年龄")]
[Range(1, int.MaxValue, ErrorMessage = "请输入大于等于1的数")]
public int Age { get; set; }

4. 正则表达式验证

对于需要满足特定格式的字段,可以使用 [RegularExpression(pattern, ErrorMessage = "错误信息")] 特性。

[DisplayName("电子邮件")]
[RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$",
ErrorMessage = "请输入正确的Email格式\n示例:abc@123.com")]
public string Email { get; set; }

5. 业务逻辑验证

远程验证

为了在客户端检查数据的唯一性,可以使用 [Remote("远程方法名", "控制器名称", ErrorMessage = "错误信息")] 特性。

[DisplayName("姓名")]
[Required(ErrorMessage = "姓名不能为空")]
[Remote("GetUser", "User", ErrorMessage = "该姓名已存在")]
public string Name { get; set; }

对应的控制器方法需要标记为 [HttpGet] 并返回 JSON 格式的数据。

[HttpifyRequest]
public ActionResult GetUser(string name)
{
return Json(name != "aa", JsonRequestBehavior.AllowGet);
}

自定义验证

如果需要自定义验证逻辑,可以创建自定义特性并继承自 ValidationAttribute 类。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class LoginUniqueAttribute : ValidationAttribute
{
private static readonly string DefaultErrorMessage = "login unique";
public LoginUniqueAttribute()
: base(DefaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return DefaultErrorMessage;
}
public override bool IsValid(object value)
{
return UserService.Check(p => p.Name == value.ToString());
}
}

总结

微软的 DataAnnotations 特性在开发过程中非常有用,无论是 Web 应用还是 Windows Form 应用,都可以通过这些特性轻松实现数据验证。 MVC 框架在验证方面的支持尤为全面,非常适合开发者快速构建高效的数据验证逻辑。

转载地址:http://vguuk.baihongyu.com/

你可能感兴趣的文章
Oracle 11g数据库安装和卸载教程
查看>>
Oracle 11g数据库成功安装创建详细步骤
查看>>
Oracle 11g超详细安装步骤
查看>>
Oracle 12c中的MGMTDB
查看>>
Oracle 12c安装报错Installation failed to access the temporary location(无法访问临时位置)...
查看>>
Oracle 9i数据库管理教程
查看>>
ORACLE Active dataguard 一个latch: row cache objects BUG
查看>>
oracle avg、count、max、min、sum、having、any、all、nvl的用法
查看>>
Oracle BEQ方式连接配置
查看>>
oracle Blob保存方式,oracle 存储过程操作blob
查看>>
Oracle BMW Racing sailing vessel帆船图
查看>>
ORACLE Bug 4431215 引发的血案—原因分析篇
查看>>
Oracle cmd乱码
查看>>
Oracle Corp甲骨文公司推出Oracle NoSQL数据库2.0版
查看>>
oracle dblink 创建使用 垮库转移数据
查看>>
oracle dblink结合同义词的用法 PLS-00352:无法访问另一数据库
查看>>
Oracle dbms_job.submit参数错误导致问题(ora-12011 无法执行1作业)
查看>>
oracle dg switchover,DG Switchover fails
查看>>
Oracle E-Business Suite软件 任意文件上传漏洞(CVE-2022-21587)
查看>>
Oracle EBS OPM 发放生产批
查看>>