You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QML TextInput如何通过inputMask实现多条件掩码及数值校验

QML TextInput多规则inputMask实现方案

QML原生inputMask仅支持单一固定格式的输入限制,不支持或逻辑的多规则直接配置,你之前写的("9999" || "9999-9999")是JS逻辑或运算,永远只会返回第一个真值字符串"9999",自然无法实现预期效果。

可以通过「动态切换inputMask + 自定义数值校验」的组合方案实现需求,具体逻辑如下:

  • 初始状态使用9999作为掩码,允许用户输入4位纯数字
  • 监听输入内容,当用户输入到第5位、且字符为-时,自动切换掩码为9999-9999,支持继续输入后4位数字
  • 当用户删除内容到长度≤4时,自动切回9999掩码,不强制要求输入连字符和后续数字
  • 输入完整xxxx-xxxx格式时,额外校验连字符右侧数值是否大于左侧,不符合则标记输入无效

完整可运行示例代码

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    width: 400
    height: 200
    visible: true

    Column {
        anchors.centerIn: parent
        spacing: 12

        TextInput {
            id: numInput
            width: 220
            padding: 8
            font.pixelSize: 16
            border.width: 1
            border.color: valid ? "#ccc" : "red"
            radius: 4
            anchors.horizontalCenter: parent.horizontalCenter

            // 初始掩码:4位数字
            inputMask: "9999"
            property bool valid: true

            onTextChanged: {
                // 动态切换掩码
                if (text.length === 5 && text[4] === '-') {
                    inputMask = "9999-9999"
                    cursorPosition = 5
                } else if (text.length <= 4 && inputMask !== "9999") {
                    inputMask = "9999"
                }

                // 数值大小校验
                valid = true
                if (text.length === 9 && inputMask === "9999-9999") {
                    const left = parseInt(text.slice(0,4))
                    const right = parseInt(text.slice(5))
                    if (right <= left) valid = false
                }
            }
        }

        Text {
            anchors.horizontalCenter: parent.horizontalCenter
            text: numInput.valid ? "输入符合要求" : "校验失败:连字符右侧数值必须大于左侧"
            color: numInput.valid ? "green" : "red"
        }
    }
}

效果说明

  • 合法输入支持:1234、1234-3456这类符合格式的内容可以正常输入
  • 非法输入拦截:非数字、非连字符的内容会被掩码自动拦截
  • 体验一致性:支持退格自动切换掩码,输入过程无卡顿,和原生inputMask使用体验一致
  • 规则校验:完整输入带连字符的格式时,自动校验数值大小关系,错误时实时提示

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 13:09:16