14.4.  Regular Expression Validation

[ fromfile: validation.xml id: regexpvalid ]

The class QRegExpValidator uses a QRegExp to validate an input string. Example 14.7, shows a main window class that contains a QRegExpValidator and some input widgets.

Example 14.7. src/validate/regexval/rinputform.h

[ . . . . ]

class RinputForm : public QWidget {
    Q_OBJECT
 public:
    explicit RinputForm(QWidget* parent=0);
    void setupForm();
 public slots:
    void computeResult();
 private:
    QLineEdit* m_PhoneEntry;
    QLabel* m_PhoneResult;
    QString m_Phone;
    static QRegExp s_PhoneFormat;
};
[ . . . . ]

We borrowed a regex from Example 14.6 and used it to initialize the static QRegExp in Example 14.8. The program takes a phone number from the user and displays it only if it is valid. Note that, in reference to the question we raised in problem 3 of Section 14.1.1, the initial "1-" is optional for U.S. phone numbers.

Example 14.8. src/validate/regexval/rinputform.cpp

[ . . . . ]
QRegExp RinputForm::s_PhoneFormat(
  "(\\+?1[- ]?)?\\(?(\\d{3,3})\\)?[\\s-]?(\\d{3,3})[\\s-]?(\\d{4,4})");

RinputForm::RinputForm(QWidget* parent)
:   QWidget(parent),
    m_PhoneEntry(new QLineEdit),
    m_PhoneResult(new QLabel) {
    setupForm();
    move(500, 500); 1
}

void RinputForm::setupForm() {
    [ . . . . ]
    QRegExpValidator* 
          phoneValid(new QRegExpValidator(s_PhoneFormat, this));
    m_PhoneEntry->setValidator(phoneValid);
    connect(m_PhoneEntry, SIGNAL(returnPressed()),
            this, SLOT(computeResult()));
}

void RinputForm::computeResult() {
    m_Phone = m_PhoneEntry->text();
    if (s_PhoneFormat.exactMatch(m_Phone)) {
        QString areacode = s_PhoneFormat.cap(2);
        QString exchange = s_PhoneFormat.cap(3);
        QString number = s_PhoneFormat.cap(4);
        m_PhoneResult->setText(QString("(US/Canada) +1 %1-%2-%3")
              .arg(areacode).arg(exchange).arg(number));
    }
}
[ . . . . ]

1

Start in mid screen (approx).


The QRegExpValidator will not permit entry of any characters that would produce an Invalid result. Figure 14.4 shows a screenshot of the running program.

Figure 14.4.  Phone Number Validator

Phone Number Validator

The QValidator classes provide a powerful mechanism for validating input data. Qt provides two numerical range validators and a regular expression validator. If validation is not possible via numeric ranges or regular expressions, it is not difficult to extend and customize QValidator for custom conditions.