How would one set an input validator on a QLineEdit
such that it restricts it to a valid IP address? i.e. x.x.x.x where x must be between 0 and 255.and x can not be empty
Asked
Active
Viewed 1.1k times
3

RAM
- 2,257
- 2
- 19
- 41

Rishabh Bansal
- 51
- 1
- 1
- 9
-
Have you read the docs of `QValidator`? Start from there. You have basically two options, create your own subclass "IpValidator", or use the regular expression validators. – hyde Aug 29 '16 at 09:35
-
Possible duplicate of [How to set Input Mask and QValidator to a QLineEdit at a time in Qt?](http://stackoverflow.com/questions/23166283/how-to-set-input-mask-and-qvalidator-to-a-qlineedit-at-a-time-in-qt) – Tarod Aug 29 '16 at 11:00
2 Answers
4
You are looking for QRegExp and QValidator, to validate an IPv4 use this expresion:
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
Example:
QRegExp ipREX("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
ipREX.setCaseSensitivity(Qt::CaseInsensitive);
ipREX.setPatternSyntax(QRegExp::RegExp);
Now, use it as validator of your text lineedit:
QRegExpValidator regValidator( rx, 0 );
ui->lineEdit->setValidator( ®Validator );
Now, just read your input and the validator will validate it =). If you want to do it manually, try something like this:
ui->lineEdit->setText( "000.000.000.000" );
const QString input = ui->lineEdit->text();
// To check if the text is valid:
qDebug() << "IP validation: " << myREX.exactMatch(input);
There is another way to made it using Qt classes, QHostAddress and QAbstractSocket:
QHostAddress address(input);
if (QAbstractSocket::IPv4Protocol == address.protocol())
{
qDebug("Valid IPv4 address.");
}
else if (QAbstractSocket::IPv6Protocol == address.protocol())
{
qDebug("Valid IPv6 address.");
}
else
{
qDebug("Unknown or invalid address.");
}

mohabouje
- 3,867
- 2
- 14
- 28
-
It is taking the value greater than 255 also. and we can enter 133.133. instead of 4 parts. it is able to take less than 4 parts of ip address. Please suggest how we can validate that ip address must contain 4 parts with range 0-255 – Rishabh Bansal Aug 29 '16 at 10:40
-
See my last changes. Here's the best one I've found so far: \b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b – mohabouje Aug 29 '16 at 10:44
1
The answer is here
In short: You have to set QRegExpValidator
with the appropriate Regular Expression for IP4 adresses.

Community
- 1
- 1

Bernhard Heinrich
- 120
- 7