1.验证注解(Model)
public class Student { //默认不能为空 [Required(ErrorMessage ="姓名不能为空")] [StringLength(20)] public string Name { get; set; } //[RegularExpression(@"[1-9]|([1-9]d)|([1-9]dd)")] [Range(1,200,ErrorMessage ="年龄不合法")] public int Age { get; set; } [DataType(DataType.Password)] [Display(Name="密码")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name="重复密码")] [Compare("Password")] public string ConFirmPassword { get; set; } }
2.生成表单
@{Html.BeginForm("Register", "FormValidate", FormMethod.Post); } @*@Html.EditorForModel()*@ <p>name</p> @Html.TextBox("name") @Html.ValidationMessage("name")<br /> <p>age</p> @Html.TextBox("age") @Html.ValidationMessage("age")<br /> <p>password</p>@Html.TextBox("password") @Html.ValidationMessage("password")<br /> <p>passwordConfirm</p>@Html.TextBox("confirmPassword") @Html.ValidationMessage("confirmPassword")<br /> @Html.TextBox("sub", "submit", new { type="submit" }) @{Html.EndForm(); }