1.[Required] : 必须输入
[Required(ErrorMessage = "请输入用户名")]2.[StringLength] : 限制字符串长度
[StringLength(10, ErrorMessage = "长度不能超过10个字符")]3.[Range] : 限制取值范围
[Range(0, 120, ErrorMessage = "年龄范围在0到120岁之间")]4.[RegularExpression] : 必须符合某个正则表达式(1)直接使用RegularExpression来写表达式: [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "请输入Email格式")]
public String RegualarExpressionField { get; set; }(2)自定义特性:
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
:base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")
{
}
}5.Compare 判等比较
public string Email { get; set; }
[Compare("Email", ErrorMessage = "邮箱要相同")]
public string TEmail { get; set; }6.Remote : Ajax远程验证,返回值是bool类型 true表示验证通过
// Action方法 控制器类 请求方式
[Remote("User", "Validate", HttpMethod = "post", ErrorMessage = "用户名已经存在")]
public string UserName { get; set; }
//....
public ActionResult User()
{
//..
if(true)
{
return Json(true,JsonRequestBehavior.AllowGet);
}
else
return Json(false,JsonRequestBehavior.AllowGet);
}
7.OutputCache 页面缓存
[OutputCache(Duration=20)]//设置页面绝对缓存 缓存时间为 20秒
public ActionResult Index()
{
//详细代码
}

本文介绍了几种常用的数据验证技术,包括必填项检查、字符串长度限制、数值范围限制、正则表达式匹配、字段比较及Ajax远程验证,并探讨了如何使用OutputCache属性实现页面缓存。
514

被折叠的 条评论
为什么被折叠?



