How to check email address with qregexp

I need to verify that the text entered in qlineedit is of the form regexp, I tried using this:

void MainWindow::checkReg( QLineEdit& mail, const QCheckBox& skip, string type ) { if(type == "mail") { if( skip.checkState() != 2) { QRegExp mailREX("\\b[A-Z0-9._%+-] +@ [A-Z0-9.-]+\\.[AZ]{2,4}\\b"); mailREX.setCaseSensitivity(Qt::CaseInsensitive); mailREX.setPatternSyntax(QRegExp::Wildcard); bool regMat = mailREX.exactMatch(mail.text()); if(regMat == false) { QMessageBox *message = new QMessageBox(this); message->setWindowModality(Qt::NonModal); message->setText("Inserte los datos en el formato correcto"); message->setStandardButtons(QMessageBox::Ok); message->setWindowTitle("MainWindow"); message->setIcon(QMessageBox::Information); message->exec(); this->ok = 0; mail.clear(); } else this->ok = 1; } } } 

but every mailbox that I entered as me@me.com gets an error message. I also tried using

 int regMat = mailREX.indexIn(mail.text()); 

and he did not work.

Thanks in advance

+4
source share
2 answers

Why did you set the template syntax to wildcard ? Your code works (assuming you understand that your regular expression is simplified) with the RegExp template syntax:

 QRegExp mailREX("\\b[A-Z0-9._%+-] +@ [A-Z0-9.-]+\\.[AZ]{2,4}\\b"); mailREX.setCaseSensitivity(Qt::CaseInsensitive); mailREX.setPatternSyntax(QRegExp::RegExp); qDebug() << mailREX.exactMatch(" me@me.com "); 

prints true

+9
source

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(); } 
+8
source

Source: https://habr.com/ru/post/1394253/


All Articles