#ifndef INPUT_VALIDATOR_H #define INPUT_VALIDATOR_H #include #include #include #include #include #include #include #include #include #include #include namespace input_validator { // 全局常量定义 constexpr int MAX_TEXT_LENGTH = 255; // 文本最大长度 constexpr int MAX_INT_VALUE = std::numeric_limits::max(); // int类型最大值 constexpr double MAX_DOUBLE_VALUE = std::numeric_limits::max(); // double类型最大值 // QLineEdit 字符限制 inline void setMaxLength(QLineEdit* edit, int maxLength = MAX_TEXT_LENGTH) { if (edit) { edit->setMaxLength(maxLength); } } // QTextEdit 字符限制 - 使用事件过滤器 class TextEditLengthFilter : public QObject { public: TextEditLengthFilter(int maxLen, QTextEdit* target) : QObject(target), maxLength(maxLen) { if (target) { target->installEventFilter(this); } } protected: bool eventFilter(QObject* watched, QEvent* event) override { if (event->type() == QEvent::KeyPress) { QTextEdit* edit = qobject_cast(watched); if (edit && edit->toPlainText().length() >= maxLength) { return true; // 阻止输入 } } return QObject::eventFilter(watched, event); } private: int maxLength; }; // 安装 QTextEdit 字符限制 inline void installTextEditValidator(QTextEdit* edit, int maxLength = MAX_TEXT_LENGTH) { if (edit) { // 限制现有内容 QString text = edit->toPlainText(); if (text.length() > maxLength) { edit->setPlainText(text.left(maxLength)); } // 安装事件过滤器 new TextEditLengthFilter(maxLength, edit); } } // QSpinBox 最大值限制 inline void setIntMaxValue(QSpinBox* spinBox) { if (spinBox) { spinBox->setMaximum(MAX_INT_VALUE); } } // QDoubleSpinBox 最大值限制 inline void setDoubleMaxValue(QDoubleSpinBox* spinBox) { if (spinBox) { spinBox->setMaximum(MAX_DOUBLE_VALUE); } } // 手机号验证正则表达式 - 只能包含0-9数字和"-",不能以"-"开头或结尾,总长度不超过24 // 格式示例: 010-88889999, 13812345678 inline bool validatePhoneNumber(const QString& phoneNumber) { // 正则表达式: ^[0-9][0-9-]{0,22}[0-9]$ // - ^ 开始 // - [0-9] 第一个字符必须是数字 // - [0-9-]{0,22} 中间0-22个字符,可以是数字或"-" // - [0-9]$ 最后一个字符必须是数字 // 总长度: 1 + 0~22 + 1 = 1~24 个字符 static const QRegularExpression phoneRegex("^[0-9][0-9-]{0,22}[0-9]$"); return phoneRegex.match(phoneNumber).hasMatch(); } } // namespace input_validator #endif // INPUT_VALIDATOR_H