C#MVC的Model验证(正则)

1.验证手机号码:            

 

        [Display(Name = "电话号码")]
            [Required(ErrorMessage = "{0}不能为空!")]
            [RegularExpression(@"^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})?(\-[0-9]{1,4})?$|(^(13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$)", ErrorMessage = "请输入正确的手机号码!")]
            public string PhoneNumber { get; set; }

 

 

2.验证邮箱

        [EmailAddress]
            [Display(Name = "电子邮件")]
            [Required(ErrorMessage = "{0}不能为空!")]
            [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "请输入正确的邮箱!")]
            public string Email { get; set; }

 

            if (!ModelState.IsValid)
            {
                ///实体验证未通过
                string ErrorMsg = string.Empty;
                var ErrorsModel = ModelState?.Values;
                if (ErrorsModel != null)
                {
                    foreach (var item in ErrorsModel)
                    {
                        if (item.ValidationState == ModelValidationState.Invalid)
                        {
                            ErrorMsg += item?.Errors[0]?.ErrorMessage;
                            return Error(ErrorMsg);
                        }
                    }
                }
            }

 

posted @ 2019-07-30 18:05  蜗牛的礼物  阅读(1261)  评论(0编辑  收藏  举报