Important: Please read the Qt Code of Conduct -

Restrict user input in QLineEdit using Regex

  • I am trying to limit the user input in a QLineEdit box.
    The three requirements are:

    • String must start with a letter (upper or lower case)
    • list itemThe following characters can be any combination of letters and numbers
    • list itemTotal string length must be between 1 and 12 characters

    This is the regex I have come up with (and verified on


    When I use this with the QLIneEdit, My length is restriced to 12 chars, but I can enter illegal characters.
    If I remove the length check, I can orrectly restricted to a first letter followed by alpha-numerics but, obviously, my length is not restricted.

    How do I achieve both aspects of this regex for a QLineEdit widget?

  • You are overcomplicating it. This satisfies the requirements: [a-zA-Z][a-zA-Z0-9]{0,11}

  • @VRonin said in Restrict user input in QLineEdit using Regex:


    Ha ha - brilliant - thank you :)

    Any idea why mine did not behave as expected despite it working on regex tester? just curious now. Thanks

  • @Anthony-Steer said in Restrict user input in QLineEdit using Regex:

    just curious now

    Can you post your code?

  • @VRonin

        m_Validator.setRegularExpression( QRegularExpression(  "^(?=.{1,12}$)^[a-zA-Z][a-zA-Z0-9]*$" ) );
        ui.lineEdit->setValidator( &m_Validator );
    // where lineEdit is a QLineEdit widget
    // and m_Validator is QRegularExpressionValidator

  • Works for me...

    QLineEdit* lineEdit = new QLineEdit(this);
            lineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression("(?=.{1,12}$)^[a-zA-Z][a-zA-Z0-9]*"),this));

  • @VRonin
    That is bizarre, apart from the fact that my widget is created in the designer, my code is now identical to yours and I find that I can enter numbers as the first character. I don;t know if it makes a difference but I am using Qt5.13.0.

    But anyway, thanks for your help.

    Best Regards


  • You will be able to enter anything you like because anything you start entering might eventually become acceptable because you edit it. If you try to finish editing (exit the widget) while the content is unacceptable, QLineEdit::acceptableInput() will return false. As a result, the line edit's returnPressed() and editingFinished() signals will not be emitted.

    The input mask can stop invalid input from the outset, but is a bit limited. You can subclass QLineEdit and intercept keypresses to implement a smarter filter.

Log in to reply