简体   繁体   中英

Using regex to validate email and phone fields Qt

I'm trying to use regex to validate email and phone fields (the fields are QLineEdit ).

I'm using the following example:

QString expression = "[1-9]\\d{0,3}";
QRegularExpression rx(expression);
QValidator *validator = new QRegularExpressionValidator(rx, this);

QLineEdit *edit = new QLineEdit(this);
edit->setValidator(validator);

I'm using the following expressions to validate it:

const QString Phone = "/^\+?(\d.*){3,}$/";
const QString Email = "/^.+@.+$/";

These expressions were obtained from this web site: https://projects.lukehaas.me/regexhub/

But it does not work as expected, since it is 'blocking' any input to the email and phone fields.

What regular expressions should I use to validate these fields?

Note that I don't need a much precise validation. I need basically this:

Email : any content, an @ mark, any content, dot, any content. For example: user@email.com or user_123@email.com.br

Phone : any number and the following characters ")(+- ".

You have to remove surrounding / .
You have to fix escaping, using raw string might help:

const QString Phone = R"(^\+?(\d.*){3,}$)";
const QString Email = R"(^.+@.+$)";

There exist more correct regexps to validate phone/mail btw.

I have created the following expressions to validate it:

// ((\\+?(\\d{2}))\\s?)? Matches for example +55 or 55 (optional) and an optional whitespace
// ((\\d{2})|(\\((\\d{2})\\))\\s?)? Matches for example 11 or (11) (optional) and an optional whitespace
// (\\d{3,15}) Matches at least 3 digits and at most 15 digits (required)
// (\\-(\\d{3,15}))? Matches exactly a dash and at least 3 digits and at most 15 digits (optional)
// E.g.: 1234-5678
// E.g.: 11 1234-5678
// E.g.: 11 91234-5678
// E.g.: (11) 1234-5678
// E.g.: +55 11 91234-5678
// E.g.: +55 (11) 91234-5678
// E.g.: 5511912345678
const QString Phone = "^((\\+?(\\d{2}))\\s?)?((\\d{2})|(\\((\\d{2})\\))\\s?)?(\\d{3,15})(\\-(\\d{3,15}))?$";

// [A-Z0-9a-z._-]{1,} Matches one or more occurrences of that digits (including ., _ and -)
// @ Matches exactly one @ character
// (\\.(\\w+)) Matches exactly one dot and one or more word character (e.g. ".com")
// (\\.(\\w+))? Matches one dot and one or more word character (e.g. ".br") (optional)
// E.g.: user@email.com
// E.g.: user_468@email.com.br
const QString Email = "^[A-Z0-9a-z._-]{1,}@(\\w+)(\\.(\\w+))(\\.(\\w+))?(\\.(\\w+))?$";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM