Home > Back-end >  US phone number verification in QT Creator
US phone number verification in QT Creator

Time:01-14

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

CodePudding user response:

That's a regular expression. See the QRegExp class documentation.

The original regex looks a lot closer (the one you commented out) than the one you've kept.

CodePudding user response:

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}$");
  •  Tags:  
  • Related