Search code examples
c++qt5qt-creator

US phone number verification in QT Creator


I am having a hard time getting a verification system for a US phone numbers working.

Please note that I am a self studied 'dev' that is just trying some things for curiosity and that my knowledge is very limited

okay so as mentioned i am trying to validate a US phone number from a LineEdit, the number should be in the following format +1 000-000-0000

so after some searching on google i found a post that helped me setup a verification, but i cannot get it to work for my format,

{
    //QRegExp nv("^\\+?(1 |)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{4}$");
    QRegExp nv("^\\+1(\\d{10})$");
    nv.setPatternSyntax(QRegExp::RegExp);
    bool regMat = nv.exactMatch(num);
    if(regMat == false)
    {
    QMessageBox *message = new QMessageBox(this);
    message->setWindowModality(Qt::NonModal);
    message->setText("Please insert a valid phone number");
    message->setStandardButtons(QMessageBox::Ok);
    message->setWindowTitle("ERROR");
    message->setIcon(QMessageBox::Information);
    message->exec();
    ui->edtCustPhone->setFocus();
    ui->edtCustPhone->selectAll();
    return false;
    }else{
    return true;
    }
};

now I'm not sure what language this is (I'm guessing JavaScript)

("^\\+?(1 |)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{4}$")

but I cannot seem to get my head around why it is not accepting number in the format that I want, and keeps prompting the error message


Solution

  • I got this working using a site that someone on discordd suggested: https://ihateregex.io/expr/phone/#

    turns out my REGEX

    ("^\\+?(1 |)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{4}$")
    

    has one to many

    [0-9]{3}
    

    iterations... and these where also stated incorrectly:

    +(-|)
    

    after some testing I got this to to work for me:

     QRegExp nv("^\\+?(1 |)[0-9]{3}\\-[0-9]{3}\\-[0-9]{4}$");