aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Wizards/Util/ClassNameValidationRule.cs
blob: 2efcf107019a44301dfd3e7d1b160711da58abb5 (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
/***************************************************************************************************
 Copyright (C) 2024 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
***************************************************************************************************/

using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace QtVsTools.Wizards.Util
{
    internal class ClassNameValidationRule : VCLanguageManagerValidationRule
    {
        public ClassNameValidationRule()
        {
            SupportNamespaces = false;
            AllowEmptyIdentifier = false;
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value is string identifier) {
                if (AllowEmptyIdentifier && string.IsNullOrEmpty(identifier))
                    return ValidationResult.ValidResult;

                if (SupportNamespaces) {
                    var index = identifier.LastIndexOf(@"::", System.StringComparison.Ordinal);
                    if (index >= 0)
                        identifier = identifier.Substring(index + 2);
                }

                if (Regex.IsMatch(identifier, pattern) && !Vclm.IsReservedName(identifier))
                    return ValidationResult.ValidResult;
            }
            return new ValidationResult(false, @"Invalid identifier.");
        }

        public bool SupportNamespaces { get; set; }
        public bool AllowEmptyIdentifier { get; set; }

        const string pattern = @"^[a-zA-Z_][a-zA-Z0-9_]*$";
    }
}