Qt QLineEdit输入验证

时间:2016-08-29 09:23:53

标签: qt validation qregexp input-mask qregularexpression

如何在let myUrl = NSURL(string:"hostname/file.php")! NSURLSession.sharedSession().dataTaskWithURL(myUrl) { (data, response, error) in if error != nil { print(error!) } else { do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:String]] { for entry in json { if let userId = entry["id"], name = entry["name"] { print(userId, name) } } } else { print("JSON is not an array of dictionaries") } } catch let error as NSError { print(error) } } }.resume() 上设置输入验证器,以便将其限制为有效的IP地址?即x.x.x.x,其中x必须介于0到255之间.x不能为空

2 个答案:

答案 0 :(得分:2)

您正在寻找QRegExpQValidator,以验证IPv4使用此表达式:

\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

示例:

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);

现在,将它用作文本lineedit的验证器:

QRegExpValidator regValidator( rx, 0 );
ui->lineEdit->setValidator( &regValidator );

现在,只需读取您的输入,验证器将验证它=)。如果您想手动执行此操作,请尝试以下操作:

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);

还有另一种方法可以使用Qt类,QHostAddressQAbstractSocket

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.");
}

答案 1 :(得分:1)

答案是floppyforms docs

简而言之:您必须使用适当的IP4地址正则表达式设置QRegExpValidator