Rambler's Top100
Главная
Новости
Статьи
Форумы
Книги
Коды
Сообщество
Блоги
О нас
 

Логин

Email:
  Пароль:

Войти
Зарегистрироваться
Забыл пароль

Поиск

 Искать :
 
Вперед

Книги по теме

Искать:
в:
Порядок:

Исходник

Автор:

ASKant

 
Название:

ExCompareValidator

Дата: 08 December 2005
Описание: Позволяет проверять не только тип DateTime, но и отдельно Date или Time 
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=176]ExCompareValidator[/CODEPOST]
Оценка: Проголосовало 2 посетителей, средняя оценка 2.00
Оценить:
  1 using System;
  2 using System.Web;
  3 using System.Web.UI;
  4 using System.Web.UI.WebControls;
  5 using System.Collections;
  6 using System.ComponentModel;
  7 using System.Drawing.Design;
  8 using System.IO;
  9 using System.Text;
 10 using System.Text.RegularExpressions;
 11 using System.Globalization;
 12 
 13 namespace ExWebControls
 14 {
 15   /// <summary>
 16   ///
 17   /// </summary>
 18 
 19   #region ExBaseCompareValidator
 20   public enum ExValidationDataType
 21   {
 22     Currency = 6,
 23     DateTime = 5,
 24     Date = 4,
 25     Time = 3,
 26     Double = 2,
 27     Integer = 1,
 28     String = 0
 29   }
 30 
 31   public abstract class ExBaseCompareValidator : BaseValidator
 32   {
 33     protected ExBaseCompareValidator()
 34     {
 35     }
 36 
 37     protected override void AddAttributesToRender(HtmlTextWriter writer)
 38     {
 39       base.AddAttributesToRender(writer);
 40       if (base.RenderUplevel)
 41       {
 42         ExValidationDataType type1 = this.Type;
 43         if (type1 != ExValidationDataType.String)
 44         {
 45           writer.AddAttribute("type", PropertyConverter.EnumToString(typeof(ExValidationDataType), type1));
 46           NumberFormatInfo info1 = NumberFormatInfo.CurrentInfo;
 47           if (type1 == ExValidationDataType.Double)
 48           {
 49             string text1 = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
 50             writer.AddAttribute("decimalchar", text1);
 51           }
 52           else if (type1 == ExValidationDataType.Currency)
 53           {
 54             string text2 = info1.CurrencyDecimalSeparator;
 55             writer.AddAttribute("decimalchar", text2);
 56             string text3 = info1.CurrencyGroupSeparator;
 57             if (text3[0] == '\x00a0')
 58             {
 59               text3 = " ";
 60             }
 61             writer.AddAttribute("groupchar", text3);
 62             int num1 = info1.CurrencyDecimalDigits;
 63             writer.AddAttribute("digits", num1.ToString(NumberFormatInfo.InvariantInfo));
 64           }
 65           else if (type1 == ExValidationDataType.Date || type1 == ExValidationDataType.DateTime)
 66           {
 67             writer.AddAttribute("dateorder", ExBaseCompareValidator.GetDateElementOrder());
 68             writer.AddAttribute("cutoffyear", ExBaseCompareValidator.CutoffYear.ToString());
 69             int num2 = DateTime.Today.Year;
 70             int num3 = num2 - (num2 % 100);
 71             writer.AddAttribute("century", num3.ToString());
 72           }
 73         }
 74       }
 75     }
 76 
 77     public static bool CanConvert(string text, ExValidationDataType type)
 78     {
 79       object obj1 = null;
 80       return ExBaseCompareValidator.Convert(text, type, out obj1);
 81     }
 82 
 83     protected static bool Compare(string leftText, string rightText, ValidationCompareOperator op, ExValidationDataType type)
 84     {
 85       object obj1;
 86       int num1;
 87       ValidationCompareOperator operator1;
 88       if (!ExBaseCompareValidator.Convert(leftText, type, out obj1))
 89       {
 90         return false;
 91       }
 92       if (op != ValidationCompareOperator.DataTypeCheck)
 93       {
 94         object obj2;
 95         if (!ExBaseCompareValidator.Convert(rightText, type, out obj2))
 96         {
 97           return true;
 98         }
 99         switch (type)
100         {
101           case ExValidationDataType.String:
102           {
103             num1 = string.Compare((string) obj1, (string) obj2, false, CultureInfo.CurrentCulture);
104             goto Label_00B2;
105           }
106           case ExValidationDataType.Integer:
107           {
108             int num2 = (int) obj1;
109             num1 = num2.CompareTo(obj2);
110             goto Label_00B2;
111           }
112           case ExValidationDataType.Double:
113           {
114             double num3 = (double) obj1;
115             num1 = num3.CompareTo(obj2);
116             goto Label_00B2;
117           }
118           case ExValidationDataType.Date:
119           case ExValidationDataType.DateTime:
120           {
121             DateTime time1 = (DateTime) obj1;
122             num1 = time1.CompareTo(obj2);
123             goto Label_00B2;
124           }
125           case ExValidationDataType.Time:
126           {
127             TimeSpan time1 = (TimeSpan) obj1;
128             num1 = time1.CompareTo(obj2);
129             goto Label_00B2;
130           }
131           case ExValidationDataType.Currency:
132           {
133             decimal num4 = (decimal) obj1;
134             num1 = num4.CompareTo(obj2);
135             goto Label_00B2;
136           }
137         }
138       }
139       return true;
140     Label_00B2:
141       operator1 = op;
142       switch (operator1)
143       {
144         case ValidationCompareOperator.Equal:
145         {
146           return (num1 == 0);
147         }
148         case ValidationCompareOperator.NotEqual:
149         {
150           return (num1 != 0);
151         }
152         case ValidationCompareOperator.GreaterThan:
153         {
154           return (num1 > 0);
155         }
156         case ValidationCompareOperator.GreaterThanEqual:
157         {
158           return (num1 >= 0);
159         }
160         case ValidationCompareOperator.LessThan:
161         {
162           return (num1 < 0);
163         }
164         case ValidationCompareOperator.LessThanEqual:
165         {
166           return (num1 <= 0);
167         }
168       }
169       return true;
170     }
171 
172     protected static bool ConvertDate(String text, ref int year, ref int month, ref int day)
173     {
174       const string yearFirstPat = @"^\s*((\d{4})|(\d{2}))([-/]|\. ?)(\d{1,2})\4(\d{1,2})\s*$";
175       const string yearLastPat = @"^\s*(\d{1,2})([-/]|\. ?)(\d{1,2})\2((\d{4})|(\d{2}))\s*$";
176       string dateOrder = ExBaseCompareValidator.GetDateElementOrder();
177 
178       Match m = Regex.Match(text, yearFirstPat);
179       if (m.Success && (m.Groups[2].Success || (dateOrder == "ymd")))
180       {
181         day = int.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture);
182         month = int.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture);
183         if (m.Groups[2].Success)
184           year = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
185         else
186           year = ExBaseCompareValidator.GetFullYear(int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture));
187       }
188       else
189       {
190         if (dateOrder == "ymd") return false;
191         m = Regex.Match(text, yearLastPat);
192         if (!m.Success) return false;
193         if (dateOrder == "mdy")
194         {
195           day = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
196           month = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
197         }
198         else
199         {
200           day = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
201           month = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
202         }
203         if (m.Groups[5].Success)
204           year = int.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture);
205         else
206           year = ExBaseCompareValidator.GetFullYear(int.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture));
207       }
208       return true;
209     }
210 
211     protected static bool ConvertTime(String text, ref int hour, ref int minute, ref int second)
212     {
213       const string timePat = @"^\s*(\d{1,2})(\:)(\d{1,2})(\2\d{1,2})?\s*$";
214       Match m = Regex.Match(text, timePat);
215       if (m.Success)
216       {
217         hour = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
218         minute = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
219         if (m.Groups[4].Success && m.Groups[4].Value != "")
220           second = Int32.Parse(m.Groups[4].Value.Substring(1), CultureInfo.InvariantCulture);
221         else
222           second = 0;
223         return true;
224       }
225       return false;
226     }
227 
228 
229     public static bool Convert(string text, ExValidationDataType type, out object value)
230     {
231       value = null;
232       try
233       {
234         NumberFormatInfo info1;
235         int year = 0, month = 0, day = 0, hour = 0, minute = 0 , second = 0;
236         DateTime time;
237         Match match;
238         switch (type)
239         {
240           case ExValidationDataType.String:
241           {
242             value = text;
243             goto EndConvert;
244           }
245           case ExValidationDataType.Integer:
246           {
247             value = int.Parse(text, CultureInfo.InvariantCulture);
248             goto EndConvert;
249           }
250           case ExValidationDataType.Double:
251           {
252             string text1 = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
253             string text2 = @"^\s*([-\+])?(\d+)?(\" + text1 + @"(\d+))?\s*$";
254             match = Regex.Match(text, text2);
255             if (match.Success)
256             {
257               string text3 = match.Groups[1].Value + (match.Groups[2].Success ? match.Groups[2].Value : "0") + (match.Groups[4].Success ? ("." + match.Groups[4].Value) : string.Empty);
258               value = double.Parse(text3, CultureInfo.InvariantCulture);
259             }
260             goto EndConvert;
261           }
262           case ExValidationDataType.DateTime:
263           {
264             string DatePart, TimePart;
265             //Выделяем дату и время
266             string splitPat = @"(.+(?:[-/]|\. ?)\d{1,4})(\s+)(\d{1,2}\:.+)";
267             match = Regex.Match(text, splitPat);
268             if (match.Success)
269             {
270               DatePart = match.Groups[1].Value;
271               TimePart = match.Groups[3].Value;
272             }
273             else
274             {
275               splitPat = @"(.+\:\d{1,2})(\s+)(\d{1,4}(?:[-/]|\. ?).+)";
276               match = Regex.Match(text, splitPat);
277               if (match.Success)
278               {
279                 DatePart = match.Groups[3].Value;
280                 TimePart = match.Groups[1].Value;
281               }
282               else goto EndConvert;
283             }
284 
285             if (!ConvertTime(TimePart, ref hour, ref minute, ref second))
286               goto EndConvert;
287 
288             if (DateTimeFormatInfo.CurrentInfo.Calendar.GetType() == typeof(GregorianCalendar))
289             {
290               if (ConvertDate(DatePart, ref year, ref month, ref day))
291               {
292                 time = new DateTime(year, month, day, hour, minute, second);
293                 if (time != DateTime.MinValue)
294                   value = time;
295               }
296             }
297             else
298             {
299               time = DateTime.Parse(DatePart);
300               time.Add(new TimeSpan(hour, minute, second));
301               value = time;
302             }
303             goto EndConvert;
304           }
305           case ExValidationDataType.Date:
306           {
307             if (DateTimeFormatInfo.CurrentInfo.Calendar.GetType() == typeof(GregorianCalendar))
308             {
309               if (ConvertDate(text, ref year, ref month, ref day))
310               {
311                 time = new DateTime(year, month, day);
312                 if (time != DateTime.MinValue)
313                   value = time;
314               }
315             }
316             else
317             {
318               value = DateTime.Parse(text);
319             }
320             goto EndConvert;
321           }
322           case ExValidationDataType.Time:
323           {
324             if (ConvertTime(text, ref hour, ref minute, ref second))
325             {
326               time = new DateTime(1, 1, 1, hour, minute, second);
327               value = time.TimeOfDay;
328             }
329             goto EndConvert;
330           }
331           case ExValidationDataType.Currency:
332           {
333             goto ConvertCurrency;
334           }
335           default:
336           {
337             goto EndConvert;
338           }
339         }
340 
341       ConvertCurrency:
342         info1 = NumberFormatInfo.CurrentInfo;
343         string text7 = info1.CurrencyDecimalSeparator;
344         string text8 = info1.CurrencyGroupSeparator;
345         if (text8[0] == '\x00a0')
346         {
347           text8 = " ";
348         }
349         int num4 = info1.CurrencyDecimalDigits;
350         string[] textArray1 = new string[5] { @"^\s*([-\+])?(((\d+)\", text8, @")*)(\d+)", (num4 > 0) ? string.Concat(new string[5]) : string.Empty, @"?\s*$" } ;
351         string text9 = string.Concat(textArray1);
352         match = Regex.Match(text, text9);
353         if (match.Success)
354         {
355           StringBuilder builder1 = new StringBuilder();
356           builder1.Append(match.Groups[1]);
357           foreach (Capture capture1 in match.Groups[4].Captures)
358           {
359             builder1.Append(capture1);
360           }
361           builder1.Append(match.Groups[5]);
362           if (num4 > 0)
363           {
364             builder1.Append(".");
365             builder1.Append(match.Groups[7]);
366           }
367           value = decimal.Parse(builder1.ToString(), CultureInfo.InvariantCulture);
368         }
369       }
370       catch
371       {
372         value = null;
373       }
374   EndConvert:
375       return (value != null);
376     }
377 
378     protected override bool DetermineRenderUplevel()
379     {
380       if ((this.Type == ExValidationDataType.Date || this.Type == ExValidationDataType.DateTime) && (DateTimeFormatInfo.CurrentInfo.Calendar.GetType() != typeof(GregorianCalendar)))
381       {
382         return false;
383       }
384       return base.DetermineRenderUplevel();
385     }
386 
387     protected static string GetDateElementOrder()
388     {
389       string text1 = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
390       if (text1.IndexOf('y') < text1.IndexOf('M'))
391       {
392         return "ymd";
393       }
394       if (text1.IndexOf('M') < text1.IndexOf('d'))
395       {
396         return "mdy";
397       }
398       return "dmy";
399     }
400 
401     protected static int GetFullYear(int shortYear)
402     {
403       int num1 = DateTime.Today.Year;
404       int num2 = num1 - (num1 % 100);
405       if (shortYear < ExBaseCompareValidator.CutoffYear)
406       {
407         return (shortYear + num2);
408       }
409       return ((shortYear + num2) - 100);
410     }
411 
412     protected static int CutoffYear
413     {
414       get
415       {
416         return DateTimeFormatInfo.CurrentInfo.Calendar.TwoDigitYearMax;
417       }
418     }
419 
420     [Description("Data type of values for comparison."), Category("Behavior"), DefaultValue(0)]
421     public ExValidationDataType Type
422     {
423       get
424       {
425         object obj1 = this.ViewState["Type"];
426         if (obj1 != null)
427         {
428           return (ExValidationDataType) obj1;
429         }
430         return ExValidationDataType.String;
431       }
432       set
433       {
434         if ((value < ExValidationDataType.String) || (value > ExValidationDataType.Currency))
435         {
436           throw new ArgumentOutOfRangeException("value");
437         }
438         this.ViewState["Type"] = value;
439       }
440     }
441   }
442   #endregion
443 
444   #region ExCompareValidator
445   [ToolboxData("<{0}:ExCompareValidator runat=server ErrorMessage=\"CompareValidator\"></{0}:ExCompareValidator>")]
446   public class ExCompareValidator : ExBaseCompareValidator
447   {
448     public ExCompareValidator()
449     {
450     }
451 
452     protected override void AddAttributesToRender(HtmlTextWriter writer)
453     {
454       base.AddAttributesToRender(writer);
455       if (base.RenderUplevel)
456       {
457         //Точка входа клиентского скрипта
458         writer.AddAttribute("evaluationfunction", "ExCompareValidatorEvaluateIsValid");
459         if (this.ControlToCompare.Length > 0)
460         {
461           writer.AddAttribute("controltocompare", base.GetControlRenderID(this.ControlToCompare));
462           writer.AddAttribute("controlhookup", base.GetControlRenderID(this.ControlToCompare));
463         }
464         if (this.ValueToCompare.Length > 0)
465         {
466           writer.AddAttribute("valuetocompare", this.ValueToCompare);
467         }
468         if (this.Operator != ValidationCompareOperator.Equal)
469         {
470           writer.AddAttribute("operator", PropertyConverter.EnumToString(typeof(ValidationCompareOperator), this.Operator));
471         }
472       }
473     }
474 
475     protected override bool ControlPropertiesValid()
476     {
477       if (this.ControlToCompare.Length > 0)
478       {
479         base.CheckControlValidationProperty(this.ControlToCompare, "ControlToCompare");
480         if (string.Compare(base.ControlToValidate, this.ControlToCompare, true, CultureInfo.InvariantCulture) == 0)
481         {
482           throw new HttpException(string.Format("Control '{0}' cannot have the same value '{1}' for both ControlToValidate and ControlToCompare.", this.ID, this.ControlToCompare));
483         }
484       }
485       else if ((this.Operator != ValidationCompareOperator.DataTypeCheck) && !ExBaseCompareValidator.CanConvert(this.ValueToCompare, base.Type))
486       {
487         string[] textArray1 = new string[4] { this.ValueToCompare, "ValueToCompare", this.ID, PropertyConverter.EnumToString(typeof(ValidationDataType), base.Type) } ;
488         throw new HttpException(string.Format("Control '{0}' referenced by the {1} property of '{2}' cannot be validated.", textArray1));
489       }
490       return base.ControlPropertiesValid();
491     }
492 
493     protected override bool EvaluateIsValid()
494     {
495       string text1 = base.GetControlValidationValue(base.ControlToValidate);
496       if (text1.Trim().Length == 0)
497       {
498         return true;
499       }
500       string text2 = string.Empty;
501       if (this.ControlToCompare.Length > 0)
502       {
503         text2 = base.GetControlValidationValue(this.ControlToCompare);
504       }
505       else
506       {
507         text2 = this.ValueToCompare;
508       }
509       return ExBaseCompareValidator.Compare(text1, text2, this.Operator, base.Type);
510     }
511 
512     protected override void OnPreRender(EventArgs e)
513     {
514       base.OnPreRender(e);
515       this.RegisterClientScript();
516     }
517 
518     protected virtual void RegisterClientScript()
519     {
520       if (base.RenderUplevel && !this.Page.IsClientScriptBlockRegistered("WebExValidationIncludeScript"))
521       {
522         string text1 = Utils.GetScriptLocation(this.Context);
523         Utils.RegisterClientScriptFile(this.Page, "WebExValidationIncludeScript", "javascript", text1, "ExValidation.js");
524       }
525     }
526 
527     [Category("Behavior"), DefaultValue(""), TypeConverter(typeof(ValidatedControlConverter))]
528     public string ControlToCompare
529     {
530       get
531       {
532         object obj1 = this.ViewState["ControlToCompare"];
533         if (obj1 != null)
534         {
535           return (string) obj1;
536         }
537         return string.Empty;
538       }
539       set
540       {
541         this.ViewState["ControlToCompare"] = value;
542       }
543     }
544 
545     [Category("Behavior"), DefaultValue(0)]
546     public ValidationCompareOperator Operator
547     {
548       get
549       {
550         object obj1 = this.ViewState["Operator"];
551         if (obj1 != null)
552         {
553           return (ValidationCompareOperator) obj1;
554         }
555         return ValidationCompareOperator.Equal;
556       }
557       set
558       {
559         if ((value < ValidationCompareOperator.Equal) || (value > ValidationCompareOperator.DataTypeCheck))
560         {
561           throw new ArgumentOutOfRangeException("value");
562         }
563         this.ViewState["Operator"] = value;
564       }
565     }
566 
567     [Category("Behavior"), DefaultValue(""), Bindable(true)]
568     public string ValueToCompare
569     {
570       get
571       {
572         object obj1 = this.ViewState["ValueToCompare"];
573         if (obj1 != null)
574         {
575           return (string) obj1;
576         }
577         return string.Empty;
578       }
579       set
580       {
581         this.ViewState["ValueToCompare"] = value;
582       }
583     }
584   }
585   #endregion
586 }
Вернуться к списку исходников в категории Создание элементов управления
 
Наш Киев

Apartments for Rent

Rambler's Top100
Рейтинг@Mail.ru
Идея: Dimon aka Manowar Программирование: Dimon aka Manowar Дизайн: Dan Lebedev
Хостинг от компании Parking.ru
Карта сайта