1、新建一个实体类
需要引入命名空间:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class User
{
[Display(Name = "姓名")]
[Required(ErrorMessage ="用户名不能为空")]
public string username { set; get;}
[Range(1,120,ErrorMessage ="数据只能大于1小于120")]
public int age { set; get; }
}
2、前端代码
@using (Html.BeginForm("login", "home", FormMethod.Post)) {
@Html.LabelFor(Model=>Model.username)
@Html.TextBoxFor(Model=>Model.username)
@Html.ValidationMessageFor(Model=>Model.username)
@Html.LabelFor(Model => Model.age)
@Html.TextBoxFor(Model => Model.age)
@Html.ValidationMessageFor(Model => Model.age)
<input type="submit" value="提交" />
}
3、效果 4、常用的验证规则
1. 必填字段
[Required]
2. 字段长度(至多n位)
[StringLength(160)]
3.要求至少n位:
[StringLength(160, MinimumLength=3)]
4.正则验证
[RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
5. 范围
[Range(35,44)]
6.小数的情况
[Range(typeof(decimal), “0.00”, “49.99”)]
7. 比较
[RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
public string Email { get; set; }
[Compare(“Email”)]
public string EmailConfirm { get; set; }
|