Using a validator for a TextField

  • Hi all,

    In this simple example, I want when the user types a text from 3 to 10 alphabet characters, then the button below that is enabled. But this code below doesn't work and I also get this error:

    qrc:/main.qml:20:41: Unable to assign QString to QRegExp

    How to solve this please and have the project work as described above?

    import QtQuick 2.12
    import QtQuick.Window 2.2
    import QtQuick.Controls 2.12
    Window {
        visible: true
        width: 640; height: 480
        Rectangle {
            width: parent.width / 2; height: parent.height / 2
            anchors.centerIn: parent
            color: "linen"
            TextField {
                id: textFiled
                font.pixelSize: 15
                anchors.centerIn: parent
                placeholderText: qsTr("Enter the name ...")
                validator:RegExpValidator { regExp: ("[A-Za-z]{3, 10}") }
                onAccepted: myButton.enabled = true
            Button {
                id: myButton
                enabled: false
                anchors.topMargin: 15
                anchors.horizontalCenter: textFiled.horizontalCenter
                onClicked: console.log("Button clicked")

  • I used this:

    validator: RegExpValidator {
                  regExp: /[A-Za-z]{1,20}/

    And it worked.
    But how to modify it to be able to add space characters too?

  • Lifetime Qt Champion


    If it's only the space bar space char that you want, you can simply add it as last char to your character range.

  • @SGaist

    Yes, but how to make a character valid for entering texts?
    I mean in code. For example how to add that space character to the range?

    This way!?

    regExp: /[A-Za-z-" "]{1,20}/

  • Lifetime Qt Champion

    Just the space, nothing more: /[A-Za-z ]{1,20}/

  • @SGaist
    Thank you. It worked both ways.

    One other question, when I type the text and it's valid, it won't be accepted and consequently the button won't be enabled either, unless I press Enter. How to make it enabled whenever a valid text is typed in the text field, without a need for pressing Enter, please?

  • Lifetime Qt Champion

    In that case wouldn't the editingFinished be what you are looking for ?

Log in to reply