MVC4数据注释与验证 2

Using Validation Annotations

Required必须项验证属性

[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }

StringLength长度

[Required]
[StringLength(160)]
public string LastName { get; set; }
[Required]
[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }

RegularExpression正则表达式

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }

Range数字范围

[Range(35,44)]
public int Age { get; set; }
[Range(typeof(decimal), "0.00", "49.99")]
public decimal Price { get; set; }

Validation Attributes from System.Web.Mvc远程验证

[Remote("CheckUserName", "Account")]
public string UserName { get; set; }
public JsonResult CheckUserName(string username)
{
var result = Membership.FindUsersByName(username).Count == 0;
return Json(result, JsonRequestBehavior.AllowGet);
}

匹配验证

[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; }

Custom Error Messages and Localization自定义错误消息和本地化

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
ErrorMessage="Email doesn't look like a valid email address.")]
public string Email { get; set; }
[Required(ErrorMessage="Your last name is required")]
[StringLength(160, ErrorMessage="Your last name is too long")]
public string LastName { get; set; }
[Required(ErrorMessage="Your {0} is required.")]
[StringLength(160, ErrorMessage="{0} is too long.")]
public string LastName { get; set; }
[Required(ErrorMessageResourceType=typeof(ErrorMessages),
ErrorMessageResourceName="LastNameRequired")]
[StringLength(160, ErrorMessageResourceType = typeof(ErrorMessages),
ErrorMessageResourceName = "LastNameTooLong")]
public string LastName { get; set; }

Looking behind the Annotation Curtain

Validation and Model Binding验证模型绑定

[HttpPost]
public ActionResult Create(Album album)
{
// the album parameter was created via model binding
// ..
}
复制代码
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var album = storeDB.Albums.Find(id);
if(TryUpdateModel(album))
{
// ...
}
}
复制代码

Validation and Model State验证模型状态

ModelState.IsValid == false
ModelState.IsValidField("LastName") == false
ModelState["LastName"].Errors.Count > 0

验证失败的信息

var lastNameErrorMessage = ModelState["LastName"].Errors[0].ErrorMessage;

VIEW验证

@Html.ValidationMessageFor(m => m.LastName)

Controller Actions and Validation Errors控制器验证错误信息

复制代码
[HttpPost]
public ActionResult AddressAndPayment(Order newOrder)
{
if (ModelState.IsValid)
{
newOrder.Username = User.Identity.Name;
newOrder.OrderDate = DateTime.Now;
storeDB.Orders.Add(newOrder);
storeDB.SaveChanges();
// Process the order
var cart = ShoppingCart.GetCart(this);
cart.CreateOrder(newOrder);
return RedirectToAction("Complete", new { id = newOrder.OrderId });
}
// Invalid -- redisplay with errors
return View(newOrder);
}
复制代码

a啊

复制代码
[HttpPost]
public ActionResult AddressAndPayment(FormCollection collection)
{
var newOrder = new Order();
TryUpdateModel(newOrder);
if (ModelState.IsValid)
{
newOrder.Username = User.Identity.Name;
newOrder.OrderDate = DateTime.Now;
storeDB.Orders.Add(newOrder);
storeDB.SaveChanges();
// Process the order
var cart = ShoppingCart.GetCart(this);
cart.CreateOrder(newOrder);
return RedirectToAction("Complete", new { id = newOrder.OrderId });
}
// Invalid -- redisplay with errors
return View(newOrder);
}
复制代码

CUSTOM VALIDATION LOGIC自定义验证逻辑

继承ValidationAttribute

复制代码
using System.ComponentModel.DataAnnotations;
namespace MvcMusicStore.Infrastructure
{
public class MaxWordsAttribute : ValidationAttribute
{
}
}
复制代码

重写 IsValid

复制代码
public class MaxWordsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
return ValidationResult.Success;
}
}
复制代码

完整自定义验证代码

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Mvc4.Infrastructure
{
    public class MaxWordsAttribute : ValidationAttribute
    {
        public MaxWordsAttribute(int maxWords)
            : base("{0} has too many words.")
        {
            _maxWords = maxWords;
        }
        protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var valueAsString = value.ToString();
                if (valueAsString.Split(' ').Length > _maxWords)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }
        private readonly int _maxWords;
    }

}
复制代码

Model部分代码

[Required]
[StringLength(160)]
[MaxWords(10, ErrorMessage="There are too many
words in {0}")]
public string LastName { get; set; }

IValidatableObject模型中自定义验证类

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Mvc4.Infrastructure;

namespace Mvc4.Models
{
    public class Users : IValidatableObject
    {
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (LastName != null &&
            LastName.Split(' ').Length > 10)
            {
                yield return new ValidationResult("The last name has too many words!",
                new[] { "LastName" });
            }
        }
        [Required]
        [StringLength(160)]      
        public string LastName { get; set; }
    }
}
复制代码

Display

[Required]
[StringLength(160, MinimumLength=3)]
[Display(Name="First Name")]
public string FirstName { get; set; }

自动生成编辑页面

<fieldset>
<legend>Shipping Information</legend>
@Html.EditorForModel()
</fieldset>

Order控制字段顺序

复制代码
[Required]
[StringLength(160)]
[Display(Name="Last Name", Order=15001)]
[MaxWords(10, ErrorMessage="There are too many words in {0}")]
public string LastName { get; set; }
[Required]
[StringLength(160, MinimumLength=3)]
[Display(Name="First Name", Order=15000)]
public string FirstName { get; set; }
复制代码

隐藏属性Scaff oldColumn,使用EditorForModel生效

[ScaffoldColumn(false)]
public string Username { get; set; }

DisplayFormat格式化已短时间形式显示显示

[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
public decimal Time{ get; set; }

ReadOnly只读属性,在页面上可以显示但无法将值传入控制器

[ReadOnly(true)]
public decimal Total { get; set; }

DataType数据类型

[Required]
[DataType(DataType.Password)]
[Display(Name="Password")]
public string Password { get; set; }

HiddenInput隐藏字段

posted @ 2014-02-25 10:33  awp110  阅读(237)  评论(0编辑  收藏  举报