C# 格式验证
前言
asp.net mvc中的验证属性均在‘System.ComponentModel.DataAnnotations’的命名空间下,继承自ValidationAttribute的验证特性,已经定义好的验证特性大都直接应用在自定义数据类型的某个属性上根据相应的验证规则对属性值实施验证,已经定义好的有以下几个:
- RequiredAttribute:用于验证必需数据字段。
- RangeAttribute:用于验证数值字段的值是否在指定的范围之内。
- StringLengthAttribute:用于验证目标字段的字符串长度是否在指定的范围之内。
- MaxLengthAttribute/MinLengthAttribute:用于验证字符/数组字典的长度是否小于/大于指定的上/下限。
- RegularExpressionAttribute:用于验证字符串字段的格式是否与指定的正则表达式相匹配。
- CompareAttribute:用于验证目标字段的值是否与另一个字段值一致,在用户注册场景中可以用于确认两次输入密码的一致性。
- CustomValidationAttribute:指定一个用于验证目标成员的验证类型和验证方法。
这些验证全都属于服务端的验证,需要回传服务器。输入数据在服务器端验证,如果出现错误,消息还要被回传到客户端,并进行页面刷新才能显示给用户
自定义验证
mvc中所有的验证均继承ValidationAttribute基类,下面要定义CheckAgeAttribute去检验年龄必须在18到30周岁
1,首先创建一个asp.net mvc项目,在models文件夹下定义类Employee
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel.DataAnnotations;
4 using System.Linq;
5 using System.Web;
6
7 namespace MvcApplication2.Models
8 {
9 public class Employee
10 {
11 [Required]
12 public string Name { set; get; }
13 [Required]
14 [CheckAge]
15 public DateTime DOB { set; get; }
16 [Required]
17 public float Salary { set; get; }
18 }
19 }
2.在models文件夹下定义验证类CheckAgeAttribute
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel.DataAnnotations;
4 using System.Linq;
5 using System.Web;
6
7 namespace MvcApplication2.Models
8 {
9 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
10 public class CheckAgeAttribute : ValidationAttribute
11 {
12 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
13 {
14 DateTime dtv = (DateTime)value;
15 long lticks = DateTime.Now.Ticks - dtv.Ticks;
16 DateTime dtAge = new DateTime(lticks);
17 string sErrorMessage = "Age>=18 and Age<=30." +
18 "Your Age is " + dtAge.Year.ToString() + " Yrs.";
19 if (!(dtAge.Year >= 18 && dtAge.Year <= 30))
20 {
21 return new ValidationResult(sErrorMessage);
22 }
23 return ValidationResult.Success;
24 }
25 }
26 }
3.在Controllers文件夹中创建HomeController
1 using MvcApplication2.Models;
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Net;
6 using System.Net.Http;
7 using System.Web.Mvc;
8
9 namespace MvcApplication2.Controllers
10 {
11 public class HomeController : Controller
12 {
13 public ActionResult Create()
14 {
15 return View();
16 }
17
18 [HttpPost]
19 public ActionResult Create(Employee model)
20 {
21 if (!ModelState.IsValid)
22 {
23 return View("Create");
24 }
25 return View("Create");
26 }
27 }
28 }
4.创建Create视图
@Html.ValidationMessageFor(model => model.DOB)输出某个异常信息
@Html.ValidationSummary()输出包含的所有的异常信息
@Html.ValidationMessageFor(model => model.Salary, "*") 用‘*’代替输出的异常信息
1 @model MvcApplication2.Models.Employee
2 @{
3 Layout = null;
4 }
5
6 <!DOCTYPE html>
7
8 <html>
9 <head>
10 <meta name="viewport" content="width=device-width" />
11 <title>Create</title>
12 </head>
13 <body>
14 @using (Html.BeginForm())
15 {
16 <form method="post" action="@Url.Action("Create", "Home")">
17 @Html.ValidationSummary()
18
19 <p>
20 @Html.LabelFor(model => model.Name)
21 @Html.EditorFor(model => model.Name)
22 @Html.ValidationMessageFor(model => model.Name, "*")
23 </p>
24 <p>
25 @Html.LabelFor(model => model.DOB)
26 @Html.EditorFor(model => model.DOB)
27 <span style="color: red">
28 @Html.ValidationMessageFor(model => model.DOB)
29 </span>
30 </p>
31 <p>
32 @Html.LabelFor(model => model.Salary)
33 @Html.EditorFor(model => model.Salary)
34 @Html.ValidationMessageFor(model => model.Salary, "*")
35 </p>
36 <input type="submit" value="登录" />
37 </form>
38 }
39 </body>
40 </html>
5.运行结果


浙公网安备 33010602011771号