If you want to create a real QValidator for reuse, for example. QLineEdits, you also need to check the lines of intermediate email addresses, otherwise nothing will be accepted if you do not paste COPY & PASTE email address into the edit.
Here is an example for EmailValidator:
File mailvalidator.h:
#ifndef EMAILVALIDATOR_H #define EMAILVALIDATOR_H #include <QValidator> QT_BEGIN_NAMESPACE class QRegExp; QT_END_NAMESPACE class EmailValidator : public QValidator { Q_OBJECT public: explicit EmailValidator(QObject *parent = 0); State validate(QString &text, int &pos) const; void fixup(QString &text) const; private: const QRegExp m_validMailRegExp; const QRegExp m_intermediateMailRegExp; }; #endif // EMAILVALIDATOR_H
And the mailvalidator.cpp file:
#include "emailvalidator.h" EmailValidator::EmailValidator(QObject *parent) : QValidator(parent), m_validMailRegExp("[a-z0-9._%+-] +@ [a-z0-9.-]+\\.[az]{2,4}"), m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[az]*") { } QValidator::State EmailValidator::validate(QString &text, int &pos) const { Q_UNUSED(pos) fixup(text); if (m_validMailRegExp.exactMatch(text)) return Acceptable; if (m_intermediateMailRegExp.exactMatch(text)) return Intermediate; return Invalid; } void EmailValidator::fixup(QString &text) const { text = text.trimmed().toLower(); }
source share