14.4.  Regular Expression Validation

[ fromfile: validation.xml id: regexpvalid ]

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;
};
[ . . . . ]

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


Figure 14.4.  Phone Number Validator

Phone Number Validator