代码改变世界

.NET MVC model数据验证

2014-11-20 17:10  jiangys  阅读(3997)  评论(1编辑  收藏  举报

MVC提供了很方便的数据验证,只需要在model里加入相关的正则等,那么就会在前台里生成相关的验证脚本。需要引用两个js文件:

jquery.validate.min.js

jquery.validate.unobtrusive.min.js

 

Model 数据验证汇总:

        
        [Display(Name = "转入金额")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "请输入转账金额")]
        [Range(100, 20000, ErrorMessage = "输入的金额只能在100元到2万元之间")]
        [RegularExpression(@"^[1-9]\d*$", ErrorMessage = "转入的金额必须为整数")]
        public decimal Amount { get; set; }
        /// <summary>
        /// 交易密码
        /// </summary>
        [Display(Name = "交易密码")]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "{0}的长度在{2}至{1}个字符间")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "请输入交易密码")]
        [DataType(DataType.Password)]
        public string TradingPassword { get; set; }

    [StringLength(10, MinimumLength = 4, ErrorMessage = "{0}的长度必须大于{2}个字符并小于{1}个字符")]
    [Display(Name = "密码")]
    public virtual string LogPassword { get; set; }

    [StringLength(10, ErrorMessage = "{0}的长度不能大于{1}个字符")]
    [Display(Name = "姓名")]
    public virtual string RealName { get; set; }

    [Display(Name = "出生日期")]
    //[Range(typeof(DateTime), "2011-12-31", "1950-1-1", ErrorMessage = "{0}的范围是{1}到{2}")]
    public virtual DateTime Birthday { get; set; }

    [RegularExpression(@"\d{17}[\d|X]|\d{15}", ErrorMessage = "{0}的格式不正确")]
    [Display(Name = "身份证号码")]
    public virtual string IdentityNo { get; set; }

    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "{0}的格式不正确")]
    [Display(Name = "邮箱")]
    public virtual string Email { get; set; }

        [Required(ErrorMessage = "注册人邮箱不能为空")]
        [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "邮箱不正确")]
        public string Email { get; set; }