0

Is there a way to make TextInput inputMask guard multiple conditions? For example:

inputMask: ("9999" || "9999-9999") // syntax probably wrong

Accepted inputs:

  • 1234
  • 1234-3456

Edit: the right hand side input (xxxx-rhs) would also have to be greater than the left hand side.

1
  • You could use a validator for allowing multiple varying inputs. The comparison of the LHS and RHS though isn't doable with regexp I suppose. You probably need to write a custom QValidator to make this work. Commented Jun 10, 2022 at 12:27

1 Answer 1

0

The validate implementation is probably not the most efficient or readable, but it does the job. Have a look at this GitHub repository custom validator.

QValidator::State SpecialValidator::validate(QString &input, int &pos) const
{
    if (input.isEmpty())
        return QValidator::Acceptable;

    static QRegularExpression expression("^\\d{0,4}$");
    QRegularExpressionMatch expressionMatch = expression.match(input);

    if (expressionMatch.hasMatch()) {
        if (expressionMatch.captured(0).size() != 4)
            return QValidator::Intermediate;

        return QValidator::Acceptable;
    }

    static QRegularExpression advancedExpression("^(\\d{4})-(\\d{0,4})$");
    QRegularExpressionMatch advancedExpressionMatch = advancedExpression.match(input);

    if (advancedExpressionMatch.hasMatch()) {
        QString lhs = advancedExpressionMatch.captured(1);
        const QString rhs = advancedExpressionMatch.captured(2);

        if (rhs.isEmpty())
            return QValidator::Intermediate;

        if (rhs.size() == 4)
            return lhs.toInt() < rhs.toInt() ? QValidator::Acceptable : QValidator::Invalid;

        lhs.truncate(rhs.size());

        return lhs.toInt() <= rhs.toInt() ? QValidator::Intermediate : QValidator::Invalid;
    }

    return QValidator::Invalid;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.