diff --git a/autotests/phonenumbertest.h b/autotests/phonenumbertest.h --- a/autotests/phonenumbertest.h +++ b/autotests/phonenumbertest.h @@ -43,6 +43,9 @@ void shouldExportVCard21(); void shouldParseVCard21(); + + void testNormalizeNumber_data(); + void testNormalizeNumber(); }; #endif diff --git a/autotests/phonenumbertest.cpp b/autotests/phonenumbertest.cpp --- a/autotests/phonenumbertest.cpp +++ b/autotests/phonenumbertest.cpp @@ -326,3 +326,23 @@ KContacts::Addressee addr = lst.at(0); QCOMPARE(addr.phoneNumbers().count(), 3); } + +void PhoneNumberTest::testNormalizeNumber_data() +{ + QTest::addColumn("input"); + QTest::addColumn("expected"); + + QTest::newRow("empty") << QString() << QString(); + QTest::newRow("normalized") << QStringLiteral("+49123456789") << QStringLiteral("+49123456789"); + QTest::newRow("formatted") << QStringLiteral("+49(123) 456 - 789") << QStringLiteral("+49123456789"); +} + +void PhoneNumberTest::testNormalizeNumber() +{ + QFETCH(QString, input); + QFETCH(QString, expected); + + KContacts::PhoneNumber num; + num.setNumber(input); + QCOMPARE(num.normalizedNumber(), expected); +} diff --git a/src/phonenumber.h b/src/phonenumber.h --- a/src/phonenumber.h +++ b/src/phonenumber.h @@ -148,9 +148,19 @@ /** * Returns the phone number. + * This is the number as entered/stored with all formatting preserved. Preferred for display. + * @see normalizedNumber() */ Q_REQUIRED_RESULT QString number() const; + /** + * Returns the phone number normalized for dialing. + * This has all formatting stripped for passing to dialers or tel: URLs. + * @see number() + * @since 5.12 + */ + Q_REQUIRED_RESULT QString normalizedNumber() const; + /** * Sets the @p type. * Multiple types can be specified by combining them by a logical or. diff --git a/src/phonenumber.cpp b/src/phonenumber.cpp --- a/src/phonenumber.cpp +++ b/src/phonenumber.cpp @@ -136,6 +136,19 @@ return d->mNumber; } +QString PhoneNumber::normalizedNumber() const +{ + QString result; + result.reserve(d->mNumber.size()); + for (const auto &c : d->mNumber) { + if (c.isDigit() || (c == QLatin1Char('+') && result.isEmpty())) { + result.push_back(c); + } + } + return result; +} + + void PhoneNumber::setType(Type type) { d->mType = type;