Search code examples
qtqmlqtquickcontrolsqtquickcontrols2

Enable button when group of textfields are completed


I want to enable one button when, and only when, a group of text fields are filled and validated with RegExp. If you think in a web register form, I need the same behaviour in QML application. Of course, I know that it is possible using JS code but my goal is not to use it and do this with an elegant way, using only declarative qml code. Any ideas about?

This is an example:

Label {
    text: qsTr('First name')
}

TextField {
    id: firstNameTextField
}

Label {
    text: qsTr('Last name')
}

TextField {
    id: lastNameTextField
}

Label {
    text: qsTr('email')
}

// Username
TextField {
    id: emailTextField
    placeholderText: qsTr("Enter email")
    smooth: true
    validator: RegExpValidator{ regExp: /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i }
}

Label {
    text: qsTr('Password')
}

TextField {
    id: passwordTextField
}

Label {
    text: qsTr('Re-Password')
}

TextField {
    id: rePasswordTextField
}
Button {
    id:button
    enabled: // all text fields completed and validated
}

Solution

  • Here is the same solution coded in a declarative fashion:

    Row {
        TextField {
            id: field1
            placeholderText: qsTr("Enter number 1")
            validator: IntValidator {bottom: 1; top: 9;}
        }
        TextField {
            id: field2
            placeholderText: qsTr("Enter number 2")
            validator: IntValidator {bottom: 11; top: 19;}
        }
        Button {
            id: btn
            text: "Send"
            enabled: field1.acceptableInput && field2.acceptableInput
        }
    }
    

    From the Qt docs:

    acceptableInput - Returns true if the text field contains acceptable text. If a validator or input mask was set, this property will return true if the current text satisfies the validator or mask as a final string