Files
HIS-GUI/include/utils/input_validator.h
2026-04-07 17:18:33 +08:00

98 lines
2.8 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#ifndef INPUT_VALIDATOR_H
#define INPUT_VALIDATOR_H
#include <QLineEdit>
#include <QTextEdit>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <limits>
#include <QTextDocument>
#include <QObject>
#include <QEvent>
#include <QKeyEvent>
#include <QString>
#include <QRegularExpression>
namespace input_validator {
// 全局常量定义
constexpr int MAX_TEXT_LENGTH = 255; // 文本最大长度
constexpr int MAX_INT_VALUE = std::numeric_limits<int>::max(); // int类型最大值
constexpr double MAX_DOUBLE_VALUE = std::numeric_limits<double>::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<QTextEdit*>(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