Asp.Net_Mvc_后端通用验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
namespace Web.Mvc.Extensions
{
 
    #region 验证基类
    /// <summary>
    /// 通用验证基类
    /// </summary>
    public abstract class EntityValidationAttribute : ValidationAttribute
    {
        #region Constructors
        public EntityValidationAttribute(MessageType messageId, params object[] args) :
            base(() => MessageManager.Current.GetMessage(messageId, args)) { }
        #endregion
 
        #region Protected Properties
        protected virtual Regex rLetters { get { return new Regex("[a-zA-Z]{1,}"); } }
        /// <summary>
        /// 验证数字
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rDigit { get { return new Regex("[0-9]{1,}"); } }
        /// <summary>
        /// 验证邮编
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rPostNumber { get { return new Regex("^[0-9]{3,14}$"); } }
        /// <summary>
        /// 验证手机
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rMobile { get { return new Regex(@"^1[3|4|5|8][0-9]\d{8}$"); } }
        /// <summary>
        /// 验证电话
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rTelePhone { get { return new Regex(@"^[0-9]{2,4}-\d{6,8}$"); } }
        /// <summary>
        /// 验证传真
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rFex { get { return new Regex(@"/^[0-9]{2,4}-\d{6,8}$"); } }
        /// <summary>
        /// 验证Email
        /// 子类可以根据自己的逻辑去重写
        /// </summary>
        protected virtual Regex rEmail { get { return new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } }
        #endregion
 
    }
    #endregion
 
    #region 具体验证模块
    /// <summary>
    /// 为空验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class RequiredAttribute : EntityValidationAttribute
    {
        public bool AllowEmptyStrings { get; set; }
        public RequiredAttribute(MessageType messageType, params object[] args) :
            base(messageType, args)
        { }
        public override bool IsValid(object value)
        {
            return new System.ComponentModel.DataAnnotations.RequiredAttribute { AllowEmptyStrings = this.AllowEmptyStrings }.IsValid(value);
        }
    }
    /// <summary>
    /// 范围验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class RangeAttribute : EntityValidationAttribute
    {
        private System.ComponentModel.DataAnnotations.RangeAttribute innerRangeAttribute;
 
        public RangeAttribute(double minimum, double maximum, MessageType messageType, params object[] args) :
            base(messageType, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(minimum, maximum);
        }
 
        public RangeAttribute(int minimum, int maximum, MessageType messageType, params object[] args) :
            base(messageType, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(minimum, maximum);
        }
 
        public RangeAttribute(Type type, string minimum, string maximum, MessageType messageType, params object[] args) :
            base(messageType, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(type, minimum, maximum);
        }
 
        public override bool IsValid(object value)
        {
            return innerRangeAttribute.IsValid(value);
        }
    }
 
    /// <summary>
    /// Email验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class EmailAttribute : EntityValidationAttribute
    {
        public EmailAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rEmail.IsMatch(value.ToString());
        }
    }
 
    /// <summary>
    /// 数值验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class DigitAttribute : EntityValidationAttribute
    {
        public DigitAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rDigit.IsMatch(value.ToString());
        }
 
    }
 
    /// <summary>
    /// 邮编验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class PostNumberAttribute : EntityValidationAttribute
    {
        public PostNumberAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rPostNumber.IsMatch(value.ToString());
        }
 
    }
 
    /// <summary>
    /// 手机验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class MobileAttribute : EntityValidationAttribute
    {
        public MobileAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rMobile.IsMatch(value.ToString());
        }
    }
 
    /// <summary>
    /// 电话验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class TelePhoneAttribute : EntityValidationAttribute
    {
        public TelePhoneAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rTelePhone.IsMatch(value.ToString());
        }
    }
 
    /// <summary>
    /// 传真验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class FexAttribute : EntityValidationAttribute
    {
        public FexAttribute(MessageType messageType, params object[] args) :
            base(messageType, args) { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rFex.IsMatch(value.ToString());
        }
    }
    #endregion
 
    #region 验证消息返回类
    /// <summary>
    /// 消息类
    /// </summary>
    public class MessageManager
    {
        static Dictionary<MessageType, string> messages = new Dictionary<MessageType, string>();
        static MessageManager()
        {
            messages.Add(MessageType.RequiredField, "这个 \"{0}\"是必填的!");
            messages.Add(MessageType.GreaterThan, "这个 \"{0}\" 的值必须大于 \"{1}\"!");
            messages.Add(MessageType.LessThan, "这个 \"{0}\" 的值必须小于 \"{1}\"!");
            messages.Add(MessageType.EmailField, "这个 \"{0}\" 不是有效的Email地址!");
            messages.Add(MessageType.DigitField, "这个 \"{0}\" 不是有效的数字!");
            messages.Add(MessageType.PostNumberField, "这个 \"{0}\" 不是有效的邮编!");
            messages.Add(MessageType.MobileField, "这个 \"{0}\" 不是有效的手机号码!");
            messages.Add(MessageType.TelePhoneField, "这个 \"{0}\" 不是有效的电话号码!");
            messages.Add(MessageType.FexField, "这个 \"{0}\" 不是有效的传真!");
        }
        /// <summary>
        /// 得到验证异常的消息集合
        /// 对外公开
        /// </summary>
        /// <param name="messageType">异常消息ID</param>
        /// <param name="args">消息参数集合</param>
        /// <returns></returns>
        public string GetMessage(MessageType messageType, params object[] args)
        {
            return string.Format(CultureInfo.CurrentCulture, messages[messageType], args);
        }
        /// <summary>
        /// 本类的实例对象
        /// </summary>
        public static MessageManager Current = new MessageManager();
    }
 
 
 
    #endregion
 
    #region 验证类型枚举
    /// <summary>
    /// 验证消息类型
    /// </summary>
    public enum MessageType
    {
        /// <summary>
        /// 为空验证
        /// </summary>
        RequiredField,
        /// <summary>
        /// 大于验证
        /// </summary>
        GreaterThan,
        /// <summary>
        /// 小于验证
        /// </summary>
        LessThan,
        /// <summary>
        /// 邮箱验证
        /// </summary>
        EmailField,
        /// <summary>
        /// 数字验证
        /// </summary>
        DigitField,
        /// <summary>
        /// 邮编验证
        /// </summary>
        PostNumberField,
        /// <summary>
        /// 手机验证
        /// </summary>
        MobileField,
        /// <summary>
        /// 电话验证
        /// </summary>
        TelePhoneField,
        /// <summary>
        /// 传真验证
        /// </summary>
        FexField,
    }
    #endregion
 
}
 
完整的实体为:
 
  /// <summary>
    /// 人类实体
    /// </summary>
    public class Person
    {
        /// <summary>
        /// 姓名
        /// </summary>
        [DisplayName("姓名"), Required(MessageType.RequiredField, "Name")]
        public string Name { get; set; }
 
        /// <summary>
        /// 年纪
        /// </summary>
        [DisplayName("年纪"), Range(18, int.MaxValue, MessageType.GreaterThan, "Age", 18)]
        public int Age { get; set; }
 
        /// <summary>
        /// 体重
        /// </summary>
        [DisplayName("体重"), Range(int.MinValue, 160, MessageType.LessThan, "Weight", 160)]
        public double Weight { get; set; }
 
        /// <summary>
        /// 电子邮件
        /// </summary>
        [DisplayName("电子邮件"), Email(MessageType.EmailField, "电子邮件")]
        public string Email { get; set; }
 
        /// <summary>
        /// 手机
        /// </summary>
        [DisplayName("手机"), Mobile(MessageType.MobileField, "Mobile")]
        public string Mobile { get; set; }
 
        /// <summary>
        /// 电话
        /// </summary>
        [DisplayName("电话"), TelePhone(MessageType.TelePhoneField, "TelePhone")]
        public string TelePhone { get; set; }
 
        /// <summary>
        /// 邮编
        /// </summary>
        [DisplayName("邮编"), PostNumber(MessageType.PostNumberField, "PostNumber")]
        public string PostNumber { get; set; }
 
        /// <summary>
        /// 传真
        /// </summary>
        [DisplayName("传真"), Fex(MessageType.FexField, "Fex")]
        public string Fex { get; set; }
    }

  

posted @   彪悍的代码不需要注释  阅读(347)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
39
0
点击右上角即可分享
微信分享提示