Using Validation Annotations

Required必须项验证属性

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

StringLength长度

[Required]
[StringLength()]
public string LastName { get; set; }
[Required]
[StringLength(, MinimumLength=)]
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(,)]
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 == ;
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(, ErrorMessage="Your last name is too long")]
public string LastName { get; set; }
[Required(ErrorMessage="Your {0} is required.")]
[StringLength(, ErrorMessage="{0} is too long.")]
public string LastName { get; set; }
[Required(ErrorMessageResourceType=typeof(ErrorMessages),
ErrorMessageResourceName="LastNameRequired")]
[StringLength(, 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 >

验证失败的信息

var lastNameErrorMessage = ModelState["LastName"].Errors[].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()]
[MaxWords(, ErrorMessage="There are too many
words in {}")]
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 > )
{
yield return new ValidationResult("The last name has too many words!",
new[] { "LastName" });
}
}
[Required]
[StringLength()]
public string LastName { get; set; }
}
}

Display

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

自动生成编辑页面

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

Order控制字段顺序

[Required]
[StringLength()]
[Display(Name="Last Name", Order=)]
[MaxWords(, ErrorMessage="There are too many words in {0}")]
public string LastName { get; set; }
[Required]
[StringLength(, MinimumLength=)]
[Display(Name="First Name", Order=)]
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隐藏字段

MVC4数据注释与验证的更多相关文章

  1. MVC4数据注释与验证 2

    Using Validation Annotations Required必须项验证属性 [Required] public string FirstName { get; set; } [Requi ...

  2. MVC4数据注解和验证

    model中的验证注解特性: public class StuInfo { public int ID { get; set;} [Display(Name = "姓名")] // ...

  3. MVC4 数据验证、特性、自动属性总结

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    最近在做自学MVC,遇到的问题很多,索性一点点总结 ...

  4. Code First 数据注释

    Code First 数据注释 Julie Lerman http://thedatafarm.com 通过实体框架 Code First,可以使用您自己的域类表示 EF 执行查询.更改跟踪和更新函数 ...

  5. Yii 开发微信 '您提交的数据无法被验证'

    使用Yii开发微信时,出现 [error][yii\web\HttpException:] exception 'yii\web\BadRequestHttpException' with messa ...

  6. MVC中的数据注解和验证

    数据注解和验证 用户输入验证在客户端浏览器中需要执行验证逻辑. 在客户端也需要执行. 注解是一种通用机制, 可以用来向框架注入元数据, 同时, 框架不只驱动元数据的验证, 还可以在生成显示和编辑模型的 ...

  7. Entityframework Code First 系列之数据注释

    上一篇<Entityframework Code First 系列之项目搭建>讲了搭建一个Code First的控制台项目.里面有一些内容并没有扩展出来讲,因为篇幅有限.这篇针对上面内容中 ...

  8. asp.net mvc常用的数据注解和验证以及entity framework数据映射

    终于有时间整理一下asp.net mvc 和 entity framework 方面的素材了. 闲话少说,步入正题: 下面是model层的管理员信息表,也是大伙比较常用到的,看看下面的代码大伙应该不会 ...

  9. ASP.NET MVC4中的Model验证 移除指定验证信息

    MVC中通过Model在页面间传值使的程序开发变得更加的快捷,但是很多时候,我们在数据传递的时候为了确保数据的有效性,要对Model的相关属性做基本的数据验证. 不多说直接上个代码,Model的实体类 ...

随机推荐

  1. C#学习7

    一.变量交换 ; ; Console.WriteLine("开始a={0},b={1}",a,b); a = a + b; b = a - b; a = a - b; Consol ...

  2. [转] Web前端优化之 图片篇

    原文链接: http://lunax.info/archives/3101.html Web 前端优化最佳实践第六部分面向 图片(Image),这部分目前有 4 条规则.在最近的 Velocity 2 ...

  3. wijmo

    wijmo-5官网 Samples Forums Demos 1.当FlexGrid的单元格中文本过长时显示Tooltip 参考1:angular flexGrid tooltip on every ...

  4. 隐藏StatusBar 非setStatusBarHidden

    UIWindow * window = [[UIApplication sharedApplication].windows lastObject]; 隐藏 [window setWindowLeve ...

  5. ZOJ-3686 A Simple Tree Problem 线段树

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3686 题意:给定一颗有根树,每个节点有0和1两种值.有两种操作: ...

  6. ajax 加载不同数据

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  7. tinyxml2简单使用

    引入头文件 <span style="font-size:18px;">#include "HelloWorldScene.h" #include ...

  8. svn如何回滚到之前版本

    第一种情况:改动没有被提交(commit). 这种情况下,使用svn revert就能取消之前的修改. svn revert用法如下: # svn revert [-R] something 其中so ...

  9. HDU2819Swap(二分图最大匹配)

    题目链接  http://acm.hdu.edu.cn/showproblem.php?pid=2819 题目大意很明确,交换图的某些行或者是某些列(可以都换),使得这个N*N的图对角线上全部都是1. ...

  10. Regular Expression--Good parts

    匹配URL的正则表达式 <!doctype html><html lang="en"><head> <meta charset=" ...