Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Created April 23, 2020 02:00
Show Gist options
  • Save lixingcong/baf1dc132ad365eee1cfcc9233ef5667 to your computer and use it in GitHub Desktop.
Save lixingcong/baf1dc132ad365eee1cfcc9233ef5667 to your computer and use it in GitHub Desktop.
QLineEdit validator for IP and Port
class MyIPValidator : public QRegularExpressionValidator
{
// https://www.qtcentre.org/threads/6228-Ip-Address-Validation
public:
MyIPValidator(const QString& defaultString, QObject* parent = Q_NULLPTR)
: QRegularExpressionValidator(
QRegularExpression("^0*(2(5[0-5]|[0-4]\\d)|1?\\d{1,2})(\\.0*(2(5[0-5]|[0-4]\\d)|1?\\d{1,2})){3}$"), parent)
, m_defaultString(defaultString)
{}
void fixup(QString& t) const override { t = m_defaultString; }
protected:
const QString m_defaultString;
};
class MyPortValidator : public QRegularExpressionValidator
{
public:
MyPortValidator(const QString& defaultString, QObject* parent = Q_NULLPTR)
: QRegularExpressionValidator(
QRegularExpression("^()([1-9]|[1-5]?[0-9]{2,4}|6[1-4][0-9]{3}|65[1-4][0-9]{2}|655[1-2][0-9]|6553[1-5])$"),
parent)
, m_defaultString(defaultString)
{}
void fixup(QString& t) const override { t = m_defaultString; }
protected:
const QString m_defaultString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment