Email format verification with QValidator

This article shows how to verify the correctness of an email address in a QLineEdit field with QRegularExpressionValidator. The implementation highlights incorrect email address in red. The check is performed whenever the text in the email input field changes, as well as on the final form submission, i.e. whenever the user presses the Save button.

Implementation details

The header customdialog.h can be seen below. The dialog consists of an email line edit and a dialog button box with buttons Save and Close. The slot adjustTextColor() reacts to the any change of text in the email input field (the text color of email changes to red whenever the format does not satisfy the desired criteria). The correctness of the input is additionally checked on the final submission, i.e. in the save() method.

class CustomDialog : public QDialog
{
public:
    CustomDialog(QWidget* parent = Q_NULLPTR);

public slots:
    void save();
    void adjustTextColor();

private:
    QLineEdit* emailEdit;
    QDialogButtonBox* buttonBox;
    QPushButton* saveButton;
    QPushButton* closeButton;

    void createWidgets();
    void createLayout();
    void createConnections();
};

In createWidgets() we initialize the email line edit and other necessary widgets. The correctness of the input is checked with the help of a validator, here QRegularExpressionValidator, which we assocciate with QLineEdit with the help of the method QLineEdit::setValidator().

void CustomDialog::createWidgets(){
    emailEdit = new QLineEdit;
    QRegularExpression rx("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",
                          QRegularExpression::CaseInsensitiveOption);
    emailEdit->setValidator(new QRegularExpressionValidator(rx, this));

    buttonBox = new QDialogButtonBox(this);
    saveButton = buttonBox->addButton(QDialogButtonBox::Save);
    closeButton = buttonBox->addButton(QDialogButtonBox::Close);
}
The regular expression QRegularExpression rx("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b", QRegularExpression::CaseInsensitiveOption) translates into:
  1. allow one ore more occurrences of any letter, digit or special symbols ._%+-
  2. followed by @
  3. followed by one ore more occurrences of any letter, digit or special symbols ._
  4. followed by . (dot)
  5. followed by two, three or four letters
Case insensitivity is guaranteed by QRegularExpression::CaseInsensitiveOption value of the second argument.

In createConnections() we connect the QLineEdit::textChanged signal to the CustomDialog::adjustTextColor slot. This enables the check of the email format whenever the text in the email field changes. The method adjustTextColor() calls QLineEdit::hasAcceptableInput() which in the background uses QValidator to validate the correctness of the email format.

void CustomDialog::createConnections(){
    QObject::connect(saveButton,  &QPushButton::clicked, this, CustomDialog::save);
    QObject::connect(closeButton, &QPushButton::clicked, this, CustomDialog::close);
    QObject::connect(emailEdit, &QLineEdit::textChanged, this, CustomDialog::adjustTextColor);
}

void CustomDialog::adjustTextColor(){
    if(!emailEdit->hasAcceptableInput())
        emailEdit->setStyleSheet("QLineEdit { color: red;}");
    else
        emailEdit->setStyleSheet("QLineEdit { color: black;}");
}

Finally, in the method save() we also check the correctness of the input by calling QLineEdit::hasAcceptableInput(). If the line does not contain acceptable input, the user is warned with a message box. If the input is correct, we print the email address into a file.

void CustomDialog::save(){
    if(!emailEdit->hasAcceptableInput()){
        QMessageBox::warning(this, tr("Email verification"),
                             tr("Email format is incorrect."), QMessageBox::Ok);
        return;
    }

    QFile file("email.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << "Email address:" << emailEdit->text() << "\n";

    QMessageBox::information(this, tr("Email verification"),
                                   tr("Email address was saved."),
                                   QMessageBox::Ok);
}

This is all that is necessary to implement email format verification upon form submission. The entire implementation can be found in the source files above.


Created: 14.02.2017
© Walletfox.com, 2017