关于Mvc验证的
1:
[Required(ErrorMessage = "Please enter your name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[RegularExpression(".+\\@.+\\..+",
ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please specify whether you'll attend")]
public bool? WillAttend { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode =
true)] //该 ApplyFormatInEditMode 设置指定了当值进行编辑显示在一个文本框中
public DateTime ReleaseDate { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(60, MinimumLength = 3)]
public string Genre { get; set; }
2:验证的顺序
现在客户端验证,
[HttpPost]
public ActionResult Send(MessageModel model)
{
if (string.IsNullOrEmpty(model.From))
{
ModelState.AddModelError("From", "The From field is required");
}
if (string.IsNullOrEmpty(model.Message))
{
ModelState.AddModelError("Message", "The Message field is required.");
}
if (ModelState.IsValid)
{
return RedirectToAction("ThankYou");
}
ModelState.AddModelError("", "One or more errors were found");
return View(model);
然后进入服务器端验证
我们也可以创建自己的验证Creating Custom Data Annotations
To create a custom annotation, you need to create a class that inherits from ValidationAttribute, and the name
of that class must end with the suffix Attribute.
实例:我们创建一个
As an example, suppose you want to validate that the name entered
in the From field is a full name (contains a first name and last name)
//类的名称必须以Attribute结尾
public class FullNameAttribute:ValidationAttribute
{
//Override the method IsValid
public override bool IsValid(object value)
{
var nameComponents = value.ToString().Split(' ');
return nameComponents.Length == 2;
}
}
在model中使用:
[FullName(ErrorMessage="Please type your full name")]