aboutsummaryrefslogtreecommitdiffstats
path: root/SQLiteStudio3/guiSQLiteStudio/common/ipvalidator.cpp
blob: 35c8b75f33378450efe4cf4e5b0f13267002311a (plain) (blame)
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
#include "ipvalidator.h"
#include <QDebug>

QString IpValidator::reStr = "^%1(\\d%2)%1\\.%1(\\d%2)%1\\.%1(\\d%2)%1\\.%1(\\d%2)%1$";

IpValidator::IpValidator(QObject* parent) :
    QValidator(parent)
{
}

IpValidator::~IpValidator()
{
}

QValidator::State IpValidator::validate(QString& input, int&) const
{
    QString regexp = getPattern(acceptWhiteSpaces, false, whitespaceCharacter);
    QRegularExpression re(regexp);
    QRegularExpressionMatch match = re.match(input);
    if (!match.hasMatch())
        return Invalid;

    QString part;
    int value;
    bool ok;
    for (int i = 1; i <= 4; i++)
    {
        part = match.captured(i);
        if (part.isEmpty())
        {
            if (acceptEmptyParts)
                continue;
            else
                return Invalid;
        }

        value = part.toInt(&ok);
        if (!ok)
            return Invalid;

        if (value > 255 || value < 0)
            return Invalid;
    }

    return Acceptable;
}

bool IpValidator::getAcceptWhiteSpaces() const
{
    return acceptWhiteSpaces;
}

void IpValidator::setAcceptWhiteSpaces(bool value)
{
    acceptWhiteSpaces = value;
}
bool IpValidator::getAcceptEmptyParts() const
{
    return acceptEmptyParts;
}

void IpValidator::setAcceptEmptyParts(bool value)
{
    acceptEmptyParts = value;
}
QChar IpValidator::getWhitespaceCharacter() const
{
    return whitespaceCharacter;
}

void IpValidator::setWhitespaceCharacter(const QChar& value)
{
    whitespaceCharacter = value;
}

bool IpValidator::check(const QString& input, bool acceptWhiteSpaces)
{
    QString regexp = getPattern(acceptWhiteSpaces, true, ' ');
    QRegularExpression re(regexp);
    return re.match(input).hasMatch();
}

QString IpValidator::getPattern(bool acceptWhiteSpaces, bool requireFull, QChar whitespaceCharacter)
{
    QString countChar = requireFull ? "+" : "*";
    if (acceptWhiteSpaces)
    {
        if (whitespaceCharacter == ' ')
            return reStr.arg("\\s*", countChar);
        else
            return reStr.arg(whitespaceCharacter + QString("*"), countChar);
    }
    else
        return reStr.arg("", countChar);
}