首先看看mvc自己是怎么做的
1、新建Person类
public class Person
{
[DisplayName("First Name"), StringLength(10)]
public string FirstName { get; set; }
[DisplayName("Middle Name"), StringLength(50)]
public string MiddleName { get; set; }
[DisplayName("Last Name"), StringLength(50), Required]
public string LastName { get; set; }
[DisplayName("Birth Date"), DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[DataType(DataType.EmailAddress), Required]
public string Email { get; set; }
public string Phone { get; set; }
public string Postcode { get; set; }
[DataType(DataType.MultilineText)]
public string Notes { get; set; }
}
2、HomeController中
public ActionResult Index()
{
ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
return View(new Person());
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
var person = new Person();
TryUpdateModel(person);
return View(person);
}
3、Index.aspx中
<% using (Html.BeginForm()) {%>
<%: Html.EditorForModel() %>
<input type="submit" name="submit" value="Submit" />
<% } %>
再看看结合JQuery是怎么干的
1、去http://code.google.com/p/arscloud/source/browse/trunk/MvcFutures/MvcFutures/?r=7 下载一个MicrosoftMvcJQueryValidation.js
2、添加
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>
3、在Index.aspx
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%: Html.EditorForModel() %>
<input type="submit" name="submit" value="Submit" />
<% } %>
自定义验证规则类
1、新建类EmailAttribute
public class EmailAttribute : RegularExpressionAttribute {
public EmailAttribute() : base(
@"^[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$") {
ErrorMessage = "Email is invalid";
}
}
2、Models/Person.cs:
public DateTime BirthDate { get; set; }
[DataType(DataType.EmailAddress), Required, Email]
public string Email { get; set; }
3、Global.asax.cs:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(EmailAttribute),
typeof(RegularExpressionAttributeAdapter));
}