Welcome to mirror list, hosted at ThFree Co, Russian Federation.

basecomparevalidator.cs « WebControls « UI « System.Web « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 04de8b3b4a169b644eafd16fbb01426c05006001 (plain)
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//------------------------------------------------------------------------------
// <copyright file="basecomparevalidator.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls {

    using System.ComponentModel;
    using System.Drawing;
    using System.Globalization;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using System.Text.RegularExpressions;
    using System.Text;
    using System.Web.Util;


    /// <devdoc>
    ///    <para> Serves as the abstract base
    ///       class for validators that do typed comparisons.</para>
    /// </devdoc>
    public abstract class BaseCompareValidator : BaseValidator {


        /// <devdoc>
        ///    <para>Gets or sets the data type that specifies how the values
        ///       being compared should be interpreted.</para>
        /// </devdoc>
        [
        WebCategory("Behavior"),
        Themeable(false),
        DefaultValue(ValidationDataType.String),
        WebSysDescription(SR.RangeValidator_Type)
        ]
        public ValidationDataType Type {
            get {
                object o = ViewState["Type"];
                return((o == null) ? ValidationDataType.String : (ValidationDataType)o);
            }
            set {
                if (value < ValidationDataType.String || value > ValidationDataType.Currency) {
                    throw new ArgumentOutOfRangeException("value");
                }
                ViewState["Type"] = value;
            }
        }


        /// <devdoc>
        ///     Whether we should do culture invariant conversion against the
        ///     string value properties on the control
        /// </devdoc>
        [
        WebCategory("Behavior"),
        Themeable(false),
        DefaultValue(false),
        WebSysDescription(SR.BaseCompareValidator_CultureInvariantValues)
        ]
        public bool CultureInvariantValues {
            get {
                object o = ViewState["CultureInvariantValues"];
                return((o == null) ? false : (bool)o);
            }
            set {
                ViewState["CultureInvariantValues"] = value;
            }
        }


        /// <internalonly/>
        /// <devdoc>
        ///    AddAttributesToRender method
        /// </devdoc>
        protected override void AddAttributesToRender(HtmlTextWriter writer) {
            base.AddAttributesToRender(writer);
            if (RenderUplevel) {
                ValidationDataType type = Type;
                if (type != ValidationDataType.String) {
                    string id = ClientID;
                    HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering || IsUnobtrusive) ? writer : null;

                    AddExpandoAttribute(expandoAttributeWriter, id, "type", PropertyConverter.EnumToString(typeof(ValidationDataType), type), false);

                    NumberFormatInfo info = NumberFormatInfo.CurrentInfo;
                    if (type == ValidationDataType.Double) {
                        string decimalChar = info.NumberDecimalSeparator;
                        AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar);
                    }
                    else if (type == ValidationDataType.Currency) {
                        string decimalChar = info.CurrencyDecimalSeparator;
                        AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar);

                        string groupChar = info.CurrencyGroupSeparator;
                        // Map non-break space onto regular space for parsing
                        if (groupChar[0] == 160)
                            groupChar = " ";
                        AddExpandoAttribute(expandoAttributeWriter, id, "groupchar", groupChar);

                        int digits = info.CurrencyDecimalDigits;
                        AddExpandoAttribute(expandoAttributeWriter, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false);

                        // VSWhidbey 83165
                        int groupSize = GetCurrencyGroupSize(info);
                        if (groupSize > 0) {
                            AddExpandoAttribute(expandoAttributeWriter, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false);
                        }
                    }
                    else if (type == ValidationDataType.Date) {
                        AddExpandoAttribute(expandoAttributeWriter, id, "dateorder", GetDateElementOrder(), false);
                        AddExpandoAttribute(expandoAttributeWriter, id, "cutoffyear", CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false);

                        // VSWhidbey 504553: The changes of this bug make client-side script not
                        // using the century attribute anymore, but still generating it for
                        // backward compatibility with Everett pages.
                        int currentYear = DateTime.Today.Year;
                        int century = currentYear - (currentYear % 100);
                        AddExpandoAttribute(expandoAttributeWriter, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false);
                    }
                }
            }
        }



        /// <devdoc>
        ///    Check if the text can be converted to the type
        /// </devdoc>
        public static bool CanConvert(string text, ValidationDataType type) {
            return CanConvert(text, type, false);
        }


        public static bool CanConvert(string text, ValidationDataType type, bool cultureInvariant) {
            object value = null;
            return Convert(text, type, cultureInvariant, out value);
        }


        /// <internalonly/>
        /// <devdoc>
        ///    Return the order of date elements for the current culture
        /// </devdoc>
        protected static string GetDateElementOrder() {
            DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo;
            string shortPattern = info.ShortDatePattern;
            if (shortPattern.IndexOf('y') < shortPattern.IndexOf('M')) {
                return "ymd";
            }
            else if (shortPattern.IndexOf('M') < shortPattern.IndexOf('d')) {
                return "mdy";
            }
            else {
                return "dmy";
            }
        }

        // VSWhidbey 83165
        private static int GetCurrencyGroupSize(NumberFormatInfo info) {
            int [] groupSizes = info.CurrencyGroupSizes;
            if (groupSizes != null && groupSizes.Length == 1) {
                return groupSizes[0];
            }
            else {
                return -1;
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected static int CutoffYear {
            get {
                return DateTimeFormatInfo.CurrentInfo.Calendar.TwoDigitYearMax;
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected static int GetFullYear(int shortYear) {
            Debug.Assert(shortYear >= 0 && shortYear < 100);
            return DateTimeFormatInfo.CurrentInfo.Calendar.ToFourDigitYear(shortYear);
        }


        /// <devdoc>
        ///    Try to convert the test into the validation data type
        /// </devdoc>
        protected static bool Convert(string text, ValidationDataType type, out object value) {
            return Convert(text, type, false, out value);
        }


        protected static bool Convert(string text, ValidationDataType type, bool cultureInvariant, out object value) {

            value = null;
            try {
                switch (type) {
                    case ValidationDataType.String:
                        value = text;
                        break;

                    case ValidationDataType.Integer:
                        value = Int32.Parse(text, CultureInfo.InvariantCulture);
                        break;

                    case ValidationDataType.Double: {
                        string cleanInput;
                        if (cultureInvariant) {
                            cleanInput = ConvertDouble(text, CultureInfo.InvariantCulture.NumberFormat);
                        }
                        else {
                            cleanInput = ConvertDouble(text, NumberFormatInfo.CurrentInfo);
                        }

                        if (cleanInput != null) {
                            value = Double.Parse(cleanInput, CultureInfo.InvariantCulture);
                        }
                        break;
                    }

                    case ValidationDataType.Date: {
                        if (cultureInvariant) {
                            value = ConvertDate(text, "ymd");
                        }
                        else {
                            // if the calendar is not gregorian, we should not enable client-side, so just parse it directly:
                            if (!(DateTimeFormatInfo.CurrentInfo.Calendar.GetType() == typeof(GregorianCalendar))) {
                                value = DateTime.Parse(text, CultureInfo.CurrentCulture);
                                break;
                            }

                            string dateElementOrder = GetDateElementOrder();
                            value = ConvertDate(text, dateElementOrder);
                        }
                        break;
                    }

                    case ValidationDataType.Currency: {
                        string cleanInput;
                        if (cultureInvariant) {
                            cleanInput = ConvertCurrency(text, CultureInfo.InvariantCulture.NumberFormat);
                        }
                        else {
                            cleanInput = ConvertCurrency(text, NumberFormatInfo.CurrentInfo);
                        }

                        if (cleanInput != null) {
                            value = Decimal.Parse(cleanInput, CultureInfo.InvariantCulture);
                        }
                        break;
                    }
                }
            }
            catch {
                value = null;
            }
            return (value != null);
        }

        private static string ConvertCurrency(string text, NumberFormatInfo info) {
            string decimalChar = info.CurrencyDecimalSeparator;
            string groupChar = info.CurrencyGroupSeparator;

            // VSWhidbey 83165
            string beginGroupSize, subsequentGroupSize;
            int groupSize = GetCurrencyGroupSize(info);
            if (groupSize > 0) {
                string groupSizeText = groupSize.ToString(NumberFormatInfo.InvariantInfo);
                beginGroupSize = "{1," + groupSizeText + "}";
                subsequentGroupSize = "{" + groupSizeText + "}";
            }
            else {
                beginGroupSize = subsequentGroupSize = "+";
            }

            // Map non-break space onto regular space for parsing
            if (groupChar[0] == 160)
                groupChar = " ";
            int digits = info.CurrencyDecimalDigits;
            bool hasDigits = (digits > 0);
            string currencyExpression =
                "^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + groupChar + "\\d" + subsequentGroupSize + ")+)|\\d*)"
                + (hasDigits ? "\\" + decimalChar + "?(\\d{0," + digits.ToString(NumberFormatInfo.InvariantInfo) + "})" : string.Empty)
                + "\\s*$";

            Match m = Regex.Match(text, currencyExpression);
            if (!m.Success) {
                return null;
            }

            // Make sure there are some valid digits
            if (m.Groups[2].Length == 0 && hasDigits && m.Groups[5].Length == 0) {
                return null;
            }

            return m.Groups[1].Value
                   + m.Groups[2].Value.Replace(groupChar, string.Empty)
                   + ((hasDigits && m.Groups[5].Length > 0) ? "." + m.Groups[5].Value : string.Empty);
        }

        private static string ConvertDouble(string text, NumberFormatInfo info) {
            // VSWhidbey 83156: If text is empty, it would be default to 0 for
            // backward compatibility reason.
            if (text.Length == 0) {
                return "0";
            }

            string decimalChar = info.NumberDecimalSeparator;
            string doubleExpression = "^\\s*([-\\+])?(\\d*)\\" + decimalChar + "?(\\d*)\\s*$";

            Match m = Regex.Match(text, doubleExpression);
            if (!m.Success) {
                return null;
            }

            // Make sure there are some valid digits
            if (m.Groups[2].Length == 0 && m.Groups[3].Length == 0) {
                return null;
            }

            return m.Groups[1].Value
                   + (m.Groups[2].Length > 0 ? m.Groups[2].Value : "0")
                   + ((m.Groups[3].Length > 0) ? "." + m.Groups[3].Value: string.Empty);
        }

        // ****************************************************************************************************************
        // **                                                                                                            **
        // ** NOTE: When updating the regular expressions in this method, you must also update the regular expressions   **
        // **       in WebUIValidation.js::ValidatorConvert().  The server and client regular expressions must match.    **
        // **                                                                                                            **
        // ****************************************************************************************************************
        private static object ConvertDate(string text, string dateElementOrder) {
            // always allow the YMD format, if they specify 4 digits
            string dateYearFirstExpression = "^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$";
            Match m = Regex.Match(text, dateYearFirstExpression);
            int day, month, year;
            if (m.Success && (m.Groups[2].Success || dateElementOrder == "ymd")) {
                day = Int32.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture);
                month = Int32.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture);
                if (m.Groups[2].Success) {
                    year = Int32.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
                }
                else {
                    year = GetFullYear(Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture));
                }
            }
            else {
                if (dateElementOrder == "ymd") {
                    return null;
                }

                // also check for the year last format
                string dateYearLastExpression = "^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.|\\.)?\\s*$";
                m = Regex.Match(text, dateYearLastExpression);
                if (!m.Success) {
                    return null;
                }
                if (dateElementOrder == "mdy") {
                    day = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
                    month = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
                }
                else {
                    day = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
                    month = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
                }
                if (m.Groups[5].Success) {
                    year = Int32.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture);
                } else {
                    year = GetFullYear(Int32.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture));
                }
            }
            return new DateTime(year, month, day);
        }


        /// <devdoc>
        ///    Compare two strings using the type and operator
        /// </devdoc>
        protected static bool Compare(string leftText, string rightText, ValidationCompareOperator op, ValidationDataType type) {
            return Compare(leftText, false, rightText, false, op, type);
        }


        protected static bool Compare(string leftText, bool cultureInvariantLeftText,
                                      string rightText, bool cultureInvariantRightText,
                                      ValidationCompareOperator op, ValidationDataType type) {
            object leftObject;
            if (!Convert(leftText, type, cultureInvariantLeftText, out leftObject))
                return false;

            if (op == ValidationCompareOperator.DataTypeCheck)
                return true;

            object rightObject;
            if (!Convert(rightText, type, cultureInvariantRightText, out rightObject))
                return true;

            int compareResult;
            switch (type) {
                case ValidationDataType.String:
                    compareResult = String.Compare((string)leftObject, (string) rightObject, false, CultureInfo.CurrentCulture);
                    break;

                case ValidationDataType.Integer:
                    compareResult = ((int)leftObject).CompareTo(rightObject);
                    break;

                case ValidationDataType.Double:
                    compareResult = ((double)leftObject).CompareTo(rightObject);
                    break;

                case ValidationDataType.Date:
                    compareResult = ((DateTime)leftObject).CompareTo(rightObject);
                    break;

                case ValidationDataType.Currency:
                    compareResult = ((Decimal)leftObject).CompareTo(rightObject);
                    break;

                default:
                    Debug.Fail("Unknown Type");
                    return true;
            }

            switch (op) {
                case ValidationCompareOperator.Equal:
                    return compareResult == 0;
                case ValidationCompareOperator.NotEqual:
                    return compareResult != 0;
                case ValidationCompareOperator.GreaterThan:
                    return compareResult > 0 ;
                case ValidationCompareOperator.GreaterThanEqual:
                    return compareResult >= 0 ;
                case ValidationCompareOperator.LessThan:
                    return compareResult < 0 ;
                case ValidationCompareOperator.LessThanEqual:
                    return compareResult <= 0 ;
                default:
                    Debug.Fail("Unknown Operator");
                    return true;
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override bool DetermineRenderUplevel() {
            // We don't do client-side validation for dates with non gregorian calendars
            if (Type == ValidationDataType.Date && DateTimeFormatInfo.CurrentInfo.Calendar.GetType() != typeof(GregorianCalendar)) {
                return false;
            }
            return base.DetermineRenderUplevel();
        }

        internal string ConvertToShortDateString(string text) {
            // VSWhidbey 83099, 85305, we should ignore error if it happens and
            // leave text as intact when parsing the date.  We assume the caller
            // (validator) is able to handle invalid text itself.
            DateTime date;
            if (DateTime.TryParse(text, CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) {
                text = date.ToShortDateString();
            }
            return text;
        }

        internal bool IsInStandardDateFormat(string date) {
            // VSWhidbey 115454: We identify that date string with only numbers
            // and specific punctuation separators is in standard date format.
            const string standardDateExpression = "^\\s*(\\d+)([-/]|\\. ?)(\\d+)\\2(\\d+)\\s*$";
            return Regex.Match(date, standardDateExpression).Success;
        }

        internal string ConvertCultureInvariantToCurrentCultureFormat(string valueInString,
                                                                      ValidationDataType type) {
            object value;
            Convert(valueInString, type, true, out value);
            if (value is DateTime) {
                // For Date type we explicitly want the date portion only
                return ((DateTime) value).ToShortDateString();
            }
            else {
                return System.Convert.ToString(value, CultureInfo.CurrentCulture);
            }
        }
    }
}