TextField Validation of Time Input in QML

Viewed 2097

I am having a TextField which allows the user to enter time and I have used RegValidator to validate. Currently, I need to fill the particular position with "0" as soon as the user clicks on backspace. Following is the code:

TextField {
    id:textField
    text:"11:11:11"
    width:200
    height:80
    font.pointSize: 15
    color:"white"
    inputMask: "99:99:99"
    validator: RegExpValidator { regExp: /^([0-1\s]?[0-9\s]|2[0-3\s]):([0-5\s][0-9\s]):([0-5\s][0-9\s])$ / }
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    inputMethodHints: Qt.ImhDigitsOnly
}
2 Answers

when user clicks on backspace

you mean just hitting the backspace key? Then it would be something like this :

TextField {
    ..
    Keys.onBackPressed: text = "00:00:00"
}

EDIT

in order to reset just one of the numbers where the cursor is, you could do something like the following. I did not test it and maybe some of the indices are wrong, but you get the idea

TextField {
    ..
    Keys.onBackPressed: {
        var index = cursorPosition
        var char = text.charAt(index)
        if(char != ":"){
            text = text.substr(0, index) + "0"+ text.substr(index);
        }

    }
}

http://doc.qt.io/qt-5/qml-qtquick-controls-textfield.html#cursorPosition-prop

In practice you can use displayText porperty of TextInput, like this:

   TextInput {

      id: textInput

      inputMask: "00:00:00;0"

      onDisplayTextChanged: {

         // when user backspacing or deleting some character,
         // this property become as visible value: "03:01:35"
         // but text property has value: "03:1:35"

         console.log(displayText); 
      }
   }

Related