博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC4数据注释与验证 2
阅读量:6157 次
发布时间:2019-06-21

本文共 6424 字,大约阅读时间需要 21 分钟。

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 == falseModelState.IsValidField("LastName") == falseModelState["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 ordervar cart = ShoppingCart.GetCart(this);cart.CreateOrder(newOrder);return RedirectToAction("Complete", new { id = newOrder.OrderId });}// Invalid -- redisplay with errorsreturn 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 ordervar cart = ShoppingCart.GetCart(this);cart.CreateOrder(newOrder);return RedirectToAction("Complete", new { id = newOrder.OrderId });}// Invalid -- redisplay with errorsreturn 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 manywords 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
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; }

自动生成编辑页面

Shipping Information@Html.EditorForModel()

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隐藏字段

转载地址:http://pksfa.baihongyu.com/

你可能感兴趣的文章
在OSCHINA上的第一篇博文,以后好好学习吧
查看>>
Spring常用注解
查看>>
linux:yum和apt-get的区别
查看>>
Sentinel 1.5.0 正式发布,引入 Reactive 支持
查看>>
数据库之MySQL
查看>>
2019/1/15 批量删除数据库相关数据
查看>>
数据类型的一些方法
查看>>
Webpack 2 中一些常见的优化措施
查看>>
移动端响应式
查看>>
js中var、let、const的区别
查看>>
简洁优雅地实现夜间模式
查看>>
react学习总结
查看>>
在soapui上踩过的坑
查看>>
MySQL的字符集和字符编码笔记
查看>>
ntpd同步时间
查看>>
Maven编译时跳过Test
查看>>
Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结
查看>>
Apache通过mod_php5支持PHP
查看>>
java学习:jdbc连接示例
查看>>
Silverlight 如何手动打包xap
查看>>