Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt check for valid URL

Tags:

c++

url

qt

I am trying to create a Qt application which checks if a URL entered by the user into a text edit is valid.

This is what I have so far but it only ever says the URL entered is valid, even when I enter one which is not.

bool checkUrl(const QUrl &url) {
    if (!url.isValid()) {
        //qDebug(QString("Invalid URL: %1").arg(url.toString()));
        return false;
    }
    return true;
}

void MainWindow::on_pushButton_clicked()
{
    QString usertext = ui->plainTextEdit->toPlainText();
    QUrl url = QUrl::fromUserInput(usertext);
    if (checkUrl(url))
        ui->textEdit->setPlainText("Valid URL.");
    else
        ui->textEdit->setPlainText("Invalid URL.");
}

Also on the qDebug line there is an error:

/home/user/HTML/mainwindow.cpp:32: error: no matching function for call to ‘qDebug(QString)’

Does anyone know what the problem is as it keeps returning true?

like image 379
user667430 Avatar asked Dec 06 '25 05:12

user667430


2 Answers

You should use qDebug like this:

qDebug() << QString("Invalid URL: %1").arg(url.toString());

also note that QUrl::isValid() does not check syntax of url. You may want to use regular expressions to validate urls.

like image 60
sorush-r Avatar answered Dec 07 '25 20:12

sorush-r


QUrl::isValid() only basically checks if the character encoding is right. What are you considering a wrong url?

Re qDebug, the form you use basically encapsulates printf, so it doesn't work with QString. You want to do:

qDebug() << QString("Invalid URL: %1").arg(url.toString());
like image 36
Chris Browet Avatar answered Dec 07 '25 22:12

Chris Browet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!