Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qvalidator.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2012 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:critical reason:data-parser
5
6#include <qdebug.h>
7
8#include "qvalidator.h"
9#ifndef QT_NO_VALIDATOR
10#include "private/qobject_p.h"
11#include "private/qlocale_p.h"
12#include "private/qnumeric_p.h"
13#include "private/qstringiterator_p.h"
14
15#include <limits.h>
16#include <cmath>
17
18QT_BEGIN_NAMESPACE
19
20/*!
21 \class QValidator
22 \brief The QValidator class provides validation of input text.
23 \inmodule QtGui
24
25 The class itself is abstract. Two subclasses, \l QIntValidator and
26 \l QDoubleValidator, provide basic numeric-range checking, and \l
27 QRegularExpressionValidator provides general checking using a custom regular
28 expression.
29
30 If the built-in validators aren't sufficient, you can subclass
31 QValidator. The class has two virtual functions: validate() and
32 fixup().
33
34 \l validate() must be implemented by every subclass. It returns
35 \l Invalid, \l Intermediate or \l Acceptable depending on whether
36 its argument is valid (for the subclass's definition of valid).
37
38 These three states require some explanation. An \l Invalid string
39 is \e clearly invalid. \l Intermediate is less obvious: the
40 concept of validity is difficult to apply when the string is
41 incomplete (still being edited). QValidator defines \l Intermediate
42 as the property of a string that is neither clearly invalid nor
43 acceptable as a final result. \l Acceptable means that the string
44 is acceptable as a final result. One might say that any string
45 that is a plausible intermediate state during entry of an \l
46 Acceptable string is \l Intermediate.
47
48 Here are some examples:
49
50 \list
51
52 \li For a line edit that accepts integers from 10 to 1000 inclusive,
53 42 and 123 are \l Acceptable, the empty string, 5, or 1234 are \l
54 Intermediate, and "asdf" and 10114 is \l Invalid.
55
56 \li For an editable combobox that accepts URLs, any well-formed URL
57 is \l Acceptable, "http://example.com/," is \l Intermediate
58 (it might be a cut and paste action that accidentally took in a
59 comma at the end), the empty string is \l Intermediate (the user
60 might select and delete all of the text in preparation for entering
61 a new URL) and "http:///./" is \l Invalid.
62
63 \li For a spin box that accepts lengths, "11cm" and "1in" are \l
64 Acceptable, "11" and the empty string are \l Intermediate, and
65 "http://example.com" and "hour" are \l Invalid.
66
67 \endlist
68
69 \l fixup() is provided for validators that can repair some user
70 errors. The default implementation does nothing. QLineEdit, for
71 example, will call fixup() if the user presses Enter (or Return)
72 and the content is not currently valid. This allows the fixup()
73 function the opportunity of performing some magic to make an \l
74 Invalid string \l Acceptable.
75
76 A validator has a locale, set with setLocale(). It is typically used
77 to parse localized data. For example, QIntValidator and QDoubleValidator
78 use it to parse localized representations of integers and doubles.
79
80 QValidator is typically used with QLineEdit, QSpinBox and
81 QComboBox.
82
83 \sa QIntValidator, QDoubleValidator, QRegularExpressionValidator, {Line Edits Example}
84*/
85
86
87/*!
88 \enum QValidator::State
89
90 This enum type defines the states in which a validated string can
91 exist.
92
93 \value Invalid The string is \e clearly invalid.
94 \value Intermediate The string is a plausible intermediate value.
95 \value Acceptable The string is acceptable as a final result;
96 i.e. it is valid.
97*/
98
99/*!
100 \fn void QValidator::changed()
101
102 This signal is emitted when any property that may affect the validity of
103 a string has changed.
104*/
105
106/*!
107 \fn void QIntValidator::topChanged(int top)
108
109 This signal is emitted after the top property changed.
110
111 \sa QIntValidator::top(), QIntValidator::setTop(), QIntValidator::bottom(), QIntValidator::setBottom()
112 \internal
113*/
114
115/*!
116 \fn void QIntValidator::bottomChanged(int bottom)
117
118 This signal is emitted after the bottom property changed.
119
120 \sa QIntValidator::top(), QIntValidator::setTop(), QIntValidator::bottom(), QIntValidator::setBottom()
121 \internal
122*/
123
124/*!
125 \fn void QDoubleValidator::topChanged(double top)
126
127 This signal is emitted after the top property changed.
128
129 \sa QDoubleValidator::top(), QDoubleValidator::setTop(), QDoubleValidator::bottom(), QDoubleValidator::setBottom()
130 \internal
131*/
132
133/*!
134 \fn void QDoubleValidator::bottomChanged(double bottom)
135
136 This signal is emitted after the bottom property changed.
137
138 \sa QDoubleValidator::top(), QDoubleValidator::setTop(), QDoubleValidator::bottom(), QDoubleValidator::setBottom()
139 \internal
140*/
141
142/*!
143 \fn void QDoubleValidator::decimalsChanged(int decimals)
144
145 This signal is emitted after the decimals property changed.
146
147 \internal
148*/
149
150/*!
151 \fn void QDoubleValidator::notationChanged(QDoubleValidator::Notation notation)
152
153 This signal is emitted after the notation property changed.
154
155 QDoubleValidator::Notation is not a registered metatype, so for queued connections,
156 you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().
157
158 \internal
159*/
160
161class QValidatorPrivate : public QObjectPrivate{
162 Q_DECLARE_PUBLIC(QValidator)
163public:
164 QValidatorPrivate() : QObjectPrivate()
165 {
166 }
167
168 QLocale locale;
169};
170
171
172/*!
173 Sets up the validator. The \a parent parameter is
174 passed on to the QObject constructor.
175*/
176
177QValidator::QValidator(QObject * parent)
178 : QValidator(*new QValidatorPrivate, parent)
179{
180}
181
182/*!
183 Destroys the validator, freeing any storage and other resources
184 used.
185*/
186
187QValidator::~QValidator()
188{
189}
190
191/*!
192 Returns the locale for the validator. The locale is by default initialized to the same as QLocale().
193
194 \sa setLocale()
195 \sa QLocale::QLocale()
196*/
197QLocale QValidator::locale() const
198{
199 Q_D(const QValidator);
200 return d->locale;
201}
202
203/*!
204 Sets the \a locale that will be used for the validator. Unless
205 setLocale has been called, the validator will use the default
206 locale set with QLocale::setDefault(). If a default locale has not
207 been set, it is the operating system's locale.
208
209 \sa locale(), QLocale::setDefault()
210*/
211void QValidator::setLocale(const QLocale &locale)
212{
213 Q_D(QValidator);
214 if (d->locale != locale) {
215 d->locale = locale;
216 emit changed();
217 }
218}
219
220/*!
221 \fn QValidator::State QValidator::validate(QString &input, int &pos) const
222
223 This virtual function returns \l Invalid if \a input is invalid
224 according to this validator's rules, \l Intermediate if it
225 is likely that a little more editing will make the input
226 acceptable (e.g. the user types "4" into a widget which accepts
227 integers between 10 and 99), and \l Acceptable if the input is
228 valid.
229
230 The function can change both \a input and \a pos (the cursor position)
231 if required.
232*/
233
234
235/*!
236 \fn void QValidator::fixup(QString & input) const
237
238 This function attempts to change \a input to be valid according to
239 this validator's rules. It need not result in a valid string:
240 callers of this function must re-test afterwards; the default does
241 nothing.
242
243 Reimplementations of this function can change \a input even if
244 they do not produce a valid string. For example, an ISBN validator
245 might want to delete every character except digits and "-", even
246 if the result is still not a valid ISBN; a surname validator might
247 want to remove whitespace from the start and end of the string,
248 even if the resulting string is not in the list of accepted
249 surnames.
250*/
251
252void QValidator::fixup(QString &) const
253{
254}
255
256
257/*!
258 \class QIntValidator
259 \brief The QIntValidator class provides a validator that ensures
260 a string contains a valid integer within a specified range.
261 \inmodule QtGui
262
263 Example of use:
264
265 \snippet code/src_gui_util_qvalidator.cpp 0
266
267 Below we present some examples of validators. In practice they would
268 normally be associated with a widget as in the example above.
269
270 \snippet code/src_gui_util_qvalidator.cpp 1
271
272 Notice that the value \c 999 returns Intermediate. Values
273 consisting of a number of digits equal to or less than the max
274 value are considered intermediate. This is intended because the
275 digit that prevents a number from being in range is not necessarily the
276 last digit typed. This also means that an intermediate number can
277 have leading zeros.
278
279 The minimum and maximum values are set in one call with setRange(),
280 or individually with setBottom() and setTop().
281
282 QIntValidator uses its locale() to interpret the number. For example,
283 in Arabic locales, QIntValidator will accept Arabic digits.
284
285 \note The QLocale::NumberOptions set on the locale() also affect the
286 way the number is interpreted. For example, since QLocale::RejectGroupSeparator
287 is not set by default, the validator will accept group separators. It is thus
288 recommended to use QLocale::toInt() to obtain the numeric value.
289
290 \sa QDoubleValidator, QRegularExpressionValidator, QLocale::toInt(), {Line Edits Example}
291*/
292
293/*!
294 Constructs a validator with a \a parent object that
295 accepts all integers.
296*/
297
298QIntValidator::QIntValidator(QObject * parent)
299 : QIntValidator(INT_MIN, INT_MAX, parent)
300{
301}
302
303
304/*!
305 Constructs a validator with a \a parent, that accepts integers
306 from \a minimum to \a maximum inclusive.
307*/
308
309QIntValidator::QIntValidator(int minimum, int maximum,
310 QObject * parent)
311 : QValidator(parent)
312{
313 b = minimum;
314 t = maximum;
315}
316
317
318/*!
319 Destroys the validator.
320*/
321
322QIntValidator::~QIntValidator()
323{
324 // nothing
325}
326
327
328/*!
329 \fn QValidator::State QIntValidator::validate(QString &input, int &pos) const
330
331 Returns \l Acceptable if the \a input is an integer within the
332 valid range. If \a input has at most as many digits as the top of the range,
333 or is a prefix of an integer in the valid range, returns \l Intermediate.
334 Otherwise, returns \l Invalid.
335
336 If the valid range consists of just positive integers (e.g., 32 to 100) and
337 \a input is a negative integer, then Invalid is returned. (On the other
338 hand, if the range consists of negative integers (e.g., -100 to -32) and \a
339 input is a positive integer without leading plus sign, then Intermediate is
340 returned, because the user might be just about to type the minus (especially
341 for right-to-left languages).
342
343 Similarly, if the valid range is between 46 and 53, then 41 and 59 will be
344 evaluated as \l Intermediate, as otherwise the user wouldn't be able to
345 change a value from 49 to 51.
346
347 \snippet code/src_gui_util_qvalidator.cpp 2
348
349 By default, the \a pos parameter is not used by this validator.
350*/
351
352static int numDigits(qlonglong n)
353{
354 if (n == 0)
355 return 1;
356 return (int)std::log10(double(n)) + 1;
357}
358
359static qlonglong pow10(int exp)
360{
361 qlonglong result = 1;
362 for (int i = 0; i < exp; ++i)
363 result *= 10;
364 return result;
365}
366
367template <typename T> static inline
369 const QLocaleData::ParsingResult &result)
370{
371
372 using ParsingResult = QLocaleData::ParsingResult;
373 if (result.state == ParsingResult::Invalid)
374 return QValidator::Invalid;
375
376 const QLocaleData::CharBuff &buff = result.buff;
377 if (buff.isEmpty())
378 return QValidator::Intermediate;
379
380 char ch = buff[0];
381 const bool signConflicts = (min >= 0 && ch == '-') || (max < 0 && ch == '+');
382 if (signConflicts)
383 return QValidator::Invalid;
384
385 if (result.state == ParsingResult::Intermediate)
386 return QValidator::Intermediate;
387
388 return std::nullopt;
389}
390
391QValidator::State QIntValidator::validate(QString & input, int&) const
392{
393 QLocaleData::ParsingResult result =
394 locale().d->m_data->validateChars(input, QLocaleData::IntegerMode, -1,
395 locale().numberOptions());
396
397 std::optional<State> opt = initialResultCheck(b, t, result);
398 if (opt)
399 return *opt;
400
401 const QLocaleData::CharBuff &buff = result.buff;
402 QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(buff, 10);
403 if (!r.ok())
404 return Invalid;
405
406 qint64 entered = r.result;
407 if (entered >= b && entered <= t) {
408 bool ok = false;
409 locale().toInt(input, &ok);
410 return ok ? Acceptable : Intermediate;
411 }
412
413 if (entered >= 0) {
414 // the -entered < b condition is necessary to allow people to type
415 // the minus last (e.g. for right-to-left languages)
416 // The buffLength > tLength condition validates values consisting
417 // of a number of digits equal to or less than the max value as intermediate.
418
419 int buffLength = buff.size();
420 if (buff[0] == '+')
421 buffLength--;
422 const int tLength = t != 0 ? static_cast<int>(std::log10(qAbs(t))) + 1 : 1;
423
424 return (entered > t && -entered < b && buffLength > tLength) ? Invalid : Intermediate;
425 } else {
426 return (entered < b) ? Invalid : Intermediate;
427 }
428}
429
430/*! \reimp */
431void QIntValidator::fixup(QString &input) const
432{
433 auto [parseState, buff] =
434 locale().d->m_data->validateChars(input, QLocaleData::IntegerMode, -1,
435 locale().numberOptions());
436 if (parseState == QLocaleData::ParsingResult::Invalid)
437 return;
438
439 QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(buff, 10);
440 if (r.ok())
441 input = locale().toString(r.result);
442}
443
444/*!
445 Sets the range of the validator to only accept integers between \a
446 bottom and \a top inclusive.
447*/
448
449void QIntValidator::setRange(int bottom, int top)
450{
451 bool rangeChanged = false;
452 if (b != bottom) {
453 b = bottom;
454 rangeChanged = true;
455 emit bottomChanged(b);
456 }
457
458 if (t != top) {
459 t = top;
460 rangeChanged = true;
461 emit topChanged(t);
462 }
463
464 if (rangeChanged)
465 emit changed();
466}
467
468
469/*!
470 \property QIntValidator::bottom
471 \brief the validator's lowest acceptable value
472
473 By default, this property's value is derived from the lowest signed
474 integer available (-2147483648).
475
476 \sa setRange()
477*/
478void QIntValidator::setBottom(int bottom)
479{
480 setRange(bottom, top());
481}
482
483/*!
484 \property QIntValidator::top
485 \brief the validator's highest acceptable value
486
487 By default, this property's value is derived from the highest signed
488 integer available (2147483647).
489
490 \sa setRange()
491*/
492void QIntValidator::setTop(int top)
493{
494 setRange(bottom(), top);
495}
496
497/*!
498 \internal
499*/
500QValidator::QValidator(QObjectPrivate &d, QObject *parent)
501 : QObject(d, parent)
502{
503}
504
505/*!
506 \internal
507*/
508QValidator::QValidator(QValidatorPrivate &d, QObject *parent)
509 : QObject(d, parent)
510{
511}
512
513class QDoubleValidatorPrivate : public QValidatorPrivate
514{
515 Q_DECLARE_PUBLIC(QDoubleValidator)
516public:
522
524
526 void fixupWithLocale(QString &input, QLocaleData::NumberMode numMode,
527 const QLocale &locale) const;
528};
529
530
531/*!
532 \class QDoubleValidator
533
534 \brief The QDoubleValidator class provides range checking of
535 floating-point numbers.
536 \inmodule QtGui
537
538 QDoubleValidator provides an upper bound, a lower bound, and a
539 limit on the number of digits after the decimal point.
540
541 You can set the acceptable range in one call with setRange(), or
542 with setBottom() and setTop(). Set the number of decimal places
543 with setDecimals(). The validate() function returns the validation
544 state.
545
546 QDoubleValidator uses its locale() to interpret the number. For example,
547 in the German locale, "1,234" will be accepted as the fractional number
548 1.234. In Arabic locales, QDoubleValidator will accept Arabic digits.
549
550 \note The QLocale::NumberOptions set on the locale() also affect the way the
551 number is interpreted. For example, since QLocale::RejectGroupSeparator is
552 not set by default (except on the \c "C" locale), the validator will accept
553 group separators. If the string passes validation, pass it to
554 locale().toDouble() to obtain its numeric value.
555
556 \sa QIntValidator, QRegularExpressionValidator, QLocale::toDouble(), {Line Edits Example}
557*/
558
559 /*!
560 \enum QDoubleValidator::Notation
561 \since 4.3
562 This enum defines the allowed notations for entering a double.
563
564 \value StandardNotation The string is written in the standard format, a
565 whole number part optionally followed by a separator
566 and fractional part, for example \c{"0.015"}.
567
568 \value ScientificNotation The string is written in scientific form, which
569 optionally appends an exponent part to the
570 standard format, for example \c{"1.5E-2"}.
571
572 The whole number part may, as usual, include a sign. This, along with the
573 separators for fractional part, exponent and any digit-grouping, depend on
574 locale. QDoubleValidator doesn't check the placement (which would also
575 depend on locale) of any digit-grouping separators it finds, but it will
576 reject input that contains them if \l QLocale::RejectGroupSeparator is set
577 in \c locale().numberOptions().
578
579 \sa QLocale::numberOptions(), QLocale::decimalPoint(),
580 QLocale::exponential(), QLocale::negativeSign()
581*/
582
583/*!
584 Constructs a validator object with a \a parent object
585 that accepts any double.
586*/
587
588QDoubleValidator::QDoubleValidator(QObject *parent)
589 : QDoubleValidator(-HUGE_VAL, HUGE_VAL, -1, parent)
590{
591}
592
593
594/*!
595 Constructs a validator object with a \a parent object. This
596 validator will accept doubles from \a bottom to \a top inclusive,
597 with up to \a decimals digits after the decimal point.
598*/
599
600QDoubleValidator::QDoubleValidator(double bottom, double top, int decimals,
601 QObject * parent)
602 : QValidator(*new QDoubleValidatorPrivate , parent)
603{
604 b = bottom;
605 t = top;
606 dec = decimals;
607}
608
609
610/*!
611 Destroys the validator.
612*/
613
614QDoubleValidator::~QDoubleValidator()
615{
616}
617
618
619/*!
620 \fn QValidator::State QDoubleValidator::validate(QString &input, int &pos) const
621
622 Returns \l Acceptable if the string \a input is in the correct format and
623 contains a double within the valid range.
624
625 Returns \l Intermediate if \a input is in the wrong format or contains a
626 double outside the range.
627
628 Returns \l Invalid if the \a input doesn't represent a double or has too
629 many digits after the decimal point.
630
631 Note: If the valid range consists of just positive doubles (e.g. 0.0 to 100.0)
632 and \a input is a negative double then \l Invalid is returned. If notation()
633 is set to StandardNotation, and the input contains more digits before the
634 decimal point than a double in the valid range may have, \l Invalid is returned.
635 If notation() is ScientificNotation, and the input is not in the valid range,
636 \l Intermediate is returned. The value may yet become valid by changing the exponent.
637
638 By default, the \a pos parameter is not used by this validator.
639*/
640
641#ifndef LLONG_MAX
642# define LLONG_MAX Q_INT64_C(0x7fffffffffffffff)
643#endif
644
645QValidator::State QDoubleValidator::validate(QString & input, int &) const
646{
647 Q_D(const QDoubleValidator);
648
649 QLocaleData::NumberMode numMode = QLocaleData::DoubleStandardMode;
650 switch (d->notation) {
651 case StandardNotation:
652 numMode = QLocaleData::DoubleStandardMode;
653 break;
654 case ScientificNotation:
655 numMode = QLocaleData::DoubleScientificMode;
656 break;
657 }
658
659 return d->validateWithLocale(input, numMode, locale());
660}
661
662QValidator::State QDoubleValidatorPrivate::validateWithLocale(QString &input, QLocaleData::NumberMode numMode, const QLocale &locale) const
663{
664 Q_Q(const QDoubleValidator);
665 QLocaleData::ParsingResult result =
666 locale.d->m_data->validateChars(input, numMode, q->dec, locale.numberOptions());
667
668 std::optional<QValidator::State> opt = initialResultCheck(q->b, q->t, result);
669 if (opt)
670 return *opt;
671
672 bool ok = false;
673 double i = locale.toDouble(input, &ok); // returns 0.0 if !ok
674 Q_ASSERT(!qIsNaN(i)); // Would be caught by validateChars()
675 if (!ok)
676 return QValidator::Intermediate;
677
678 if (i >= q->b && i <= q->t)
679 return QValidator::Acceptable;
680
681 if (notation == QDoubleValidator::StandardNotation) {
682 double max = qMax(qAbs(q->b), qAbs(q->t));
683 qlonglong v;
684 // Need a whole number to pass to convertDoubleTo() or it fails. Use
685 // floor, as max is positive so this has the same number of digits
686 // before the decimal point, where qCeil() might take us up to a power
687 // of ten, adding a digit.
688 if (convertDoubleTo(qFloor(max), &v)) {
689 qlonglong n = pow10(numDigits(v));
690 // In order to get the highest possible number in the intermediate
691 // range we need to get 10 to the power of the number of digits
692 // after the decimal's and subtract that from the top number.
693 //
694 // For example, where q->dec == 2 and with a range of 0.0 - 9.0
695 // then the minimum possible number is 0.00 and the maximum
696 // possible is 9.99. Therefore 9.999 and 10.0 should be seen as
697 // invalid.
698 if (qAbs(i) > (n - std::pow(10, -q->dec)))
699 return QValidator::Invalid;
700 }
701 }
702
703 return QValidator::Intermediate;
704}
705
706/*!
707 \since 6.3
708 \overload
709
710 Attempts to fix the \a input string to an \l Acceptable representation of a
711 double.
712
713 The format of the number is determined by \l notation(), \l decimals(),
714 \l locale() and the latter's \l {QLocale::}{numberOptions()}.
715
716 To comply with \l notation(), when \l ScientificNotation is used, the fixed
717 value will be represented in its normalized form, which means that any
718 non-zero value will have one non-zero digit before the decimal point.
719
720 \snippet code/src_gui_util_qvalidator.cpp 7
721
722 To comply with \l decimals(), when it is \c {-1} the number of digits used
723 will be determined by \l QLocale::FloatingPointShortest. Otherwise, the
724 fractional part of the number is truncated (with rounding, as appropriate)
725 if its length exceeds \l decimals(). When \l notation() is
726 \l ScientificNotation this is done after the number has been put into its
727 normalized form.
728
729 \snippet code/src_gui_util_qvalidator.cpp 8
730
731 \note If \l decimals() is set to, and the string provides, more than
732 \c {std::numeric_limits<double>::digits10}, digits beyond that many in the
733 fractional part may be changed. The resulting string shall encode the same
734 floating-point number, when parsed to a \c double.
735*/
736void QDoubleValidator::fixup(QString &input) const
737{
738 Q_D(const QDoubleValidator);
739 const auto numberMode = d->notation == StandardNotation ? QLocaleData::DoubleStandardMode
740 : QLocaleData::DoubleScientificMode;
741
742 d->fixupWithLocale(input, numberMode, locale());
743}
744
745void QDoubleValidatorPrivate::fixupWithLocale(QString &input, QLocaleData::NumberMode numMode,
746 const QLocale &locale) const
747{
748 Q_Q(const QDoubleValidator);
749 // Passing -1 as the number of decimals, because fixup() exists to improve
750 // an Intermediate value, if it can.
751 auto [parseState, buff] =
752 locale.d->m_data->validateChars(input, numMode, -1, locale.numberOptions());
753 if (parseState == QLocaleData::ParsingResult::Invalid)
754 return;
755
756 // buff contains data in C locale.
757 bool ok = false;
758 const double entered = QByteArrayView(buff).toDouble(&ok);
759 if (ok) {
760 // Here we need to adjust the output format accordingly
761 char mode;
762 if (numMode == QLocaleData::DoubleStandardMode) {
763 mode = 'f';
764 } else {
765 // Scientific mode can be either 'e' or 'E'
766 const QString exp = locale.exponential();
767 bool preferUpper = false;
768 QStringIterator scan(exp);
769 while (!preferUpper && scan.hasNext()) {
770 const char32_t ch = scan.next();
771 if (QChar::isUpper(ch))
772 preferUpper = true;
773 }
774 if (preferUpper)
775 mode = input.contains(exp.toLower()) ? 'e' : 'E';
776 else // If case-free, we don't care which we use; otherwise, prefer lower.
777 mode = input.contains(exp.toUpper()) ? 'E' : 'e';
778 }
779 int precision;
780 if (q->dec < 0) {
781 precision = QLocale::FloatingPointShortest;
782 } else {
783 if (mode == 'f') {
784 const auto decimalPointIndex = buff.indexOf('.');
785 precision = decimalPointIndex >= 0 ? buff.size() - decimalPointIndex - 1 : 0;
786 } else {
787 auto eIndex = buff.indexOf('e');
788 // No need to check for 'E' because we can get only 'e' after a
789 // call to validateChars()
790 if (eIndex < 0)
791 eIndex = buff.size();
792 precision = eIndex - (buff.contains('.') ? 1 : 0)
793 - (buff[0] == '-' || buff[0] == '+' ? 1 : 0);
794 }
795 // Use q->dec to limit the number of decimals, because we want the
796 // fixup() result to pass validate().
797 precision = qMin(precision, q->dec);
798 }
799 input = locale.toString(entered, mode, precision);
800 }
801}
802
803/*!
804 Sets the validator to accept doubles from \a minimum to \a maximum
805 inclusive, with at most \a decimals digits after the decimal
806 point.
807
808 \note Setting the number of decimals to -1 effectively sets it to unlimited.
809 This is also the value used by a default-constructed validator.
810*/
811
812void QDoubleValidator::setRange(double minimum, double maximum, int decimals)
813{
814 bool rangeChanged = false;
815 if (b != minimum) {
816 b = minimum;
817 rangeChanged = true;
818 emit bottomChanged(b);
819 }
820
821 if (t != maximum) {
822 t = maximum;
823 rangeChanged = true;
824 emit topChanged(t);
825 }
826
827 if (dec != decimals) {
828 dec = decimals;
829 rangeChanged = true;
830 emit decimalsChanged(dec);
831 }
832 if (rangeChanged)
833 emit changed();
834}
835
836/*!
837 \overload
838
839 Sets the validator to accept doubles from \a minimum to \a maximum
840 inclusive without changing the number of digits after the decimal point.
841*/
842void QDoubleValidator::setRange(double minimum, double maximum)
843{
844 setRange(minimum, maximum, decimals());
845}
846
847/*!
848 \property QDoubleValidator::bottom
849 \brief the validator's minimum acceptable value
850
851 By default, this property contains a value of -infinity.
852
853 \sa setRange()
854*/
855
856void QDoubleValidator::setBottom(double bottom)
857{
858 setRange(bottom, top(), decimals());
859}
860
861
862/*!
863 \property QDoubleValidator::top
864 \brief the validator's maximum acceptable value
865
866 By default, this property contains a value of infinity.
867
868 \sa setRange()
869*/
870
871void QDoubleValidator::setTop(double top)
872{
873 setRange(bottom(), top, decimals());
874}
875
876/*!
877 \property QDoubleValidator::decimals
878 \brief the validator's maximum number of digits after the decimal point
879
880 By default, this property contains a value of -1, which means any number
881 of digits is accepted.
882
883 \sa setRange()
884*/
885
886void QDoubleValidator::setDecimals(int decimals)
887{
888 setRange(bottom(), top(), decimals);
889}
890
891/*!
892 \property QDoubleValidator::notation
893 \since 4.3
894 \brief the notation of how a string can describe a number
895
896 By default, this property is set to ScientificNotation.
897
898 \sa Notation
899*/
900
901void QDoubleValidator::setNotation(Notation newNotation)
902{
903 Q_D(QDoubleValidator);
904 if (d->notation != newNotation) {
905 d->notation = newNotation;
906 emit notationChanged(d->notation);
907 emit changed();
908 }
909}
910
911QDoubleValidator::Notation QDoubleValidator::notation() const
912{
913 Q_D(const QDoubleValidator);
914 return d->notation;
915}
916
917#if QT_CONFIG(regularexpression)
918
919/*!
920 \class QRegularExpressionValidator
921 \inmodule QtGui
922 \brief The QRegularExpressionValidator class is used to check a string
923 against a regular expression.
924
925 \since 5.1
926
927 QRegularExpressionValidator uses a regular expression (regexp) to
928 determine whether an input string is \l Acceptable, \l
929 Intermediate, or \l Invalid. The regexp can either be supplied
930 when the QRegularExpressionValidator is constructed, or at a later time.
931
932 If the regexp partially matches against the string, the result is
933 considered \l Intermediate. For example, "" and "A" are \l Intermediate for
934 the regexp \b{[A-Z][0-9]} (whereas "_" would be \l Invalid).
935
936 QRegularExpressionValidator automatically wraps the regular expression in
937 the \c{\\A} and \c{\\z} anchors; in other words, it always attempts to do
938 an exact match.
939
940 Example of use:
941 \snippet code/src_gui_util_qvalidator.cpp 5
942
943 Below we present some examples of validators. In practice they would
944 normally be associated with a widget as in the example above.
945
946 \snippet code/src_gui_util_qvalidator.cpp 6
947
948 \sa QRegularExpression, QIntValidator, QDoubleValidator
949*/
950
951class QRegularExpressionValidatorPrivate : public QValidatorPrivate
952{
953 Q_DECLARE_PUBLIC(QRegularExpressionValidator)
954
955public:
956 QRegularExpression origRe; // the one set by the user
957 QRegularExpression usedRe; // the one actually used
958 void setRegularExpression(const QRegularExpression &re);
959};
960
961/*!
962 Constructs a validator with a \a parent object that accepts
963 any string (including an empty one) as valid.
964*/
965
966QRegularExpressionValidator::QRegularExpressionValidator(QObject *parent)
967 : QValidator(*new QRegularExpressionValidatorPrivate, parent)
968{
969 // origRe in the private will be an empty QRegularExpression,
970 // and therefore this validator will match any string.
971}
972
973/*!
974 Constructs a validator with a \a parent object that
975 accepts all strings that match the regular expression \a re.
976*/
977
978QRegularExpressionValidator::QRegularExpressionValidator(const QRegularExpression &re, QObject *parent)
979 : QRegularExpressionValidator(parent)
980{
981 Q_D(QRegularExpressionValidator);
982 d->setRegularExpression(re);
983}
984
985
986/*!
987 Destroys the validator.
988*/
989
990QRegularExpressionValidator::~QRegularExpressionValidator()
991{
992}
993
994/*!
995 Returns \l Acceptable if \a input is matched by the regular expression for
996 this validator, \l Intermediate if it has matched partially (i.e. could be
997 a valid match if additional valid characters are added), and \l Invalid if
998 \a input is not matched.
999
1000 In case the \a input is not matched, the \a pos parameter is set to
1001 the length of the \a input parameter; otherwise, it is not modified.
1002
1003 For example, if the regular expression is \b{\\w\\d\\d} (word-character,
1004 digit, digit) then "A57" is \l Acceptable, "E5" is \l Intermediate, and
1005 "+9" is \l Invalid.
1006
1007 \sa QRegularExpression::match()
1008*/
1009
1010QValidator::State QRegularExpressionValidator::validate(QString &input, int &pos) const
1011{
1012 Q_D(const QRegularExpressionValidator);
1013
1014 // We want a validator with an empty QRegularExpression to match anything;
1015 // since we're going to do an exact match (by using d->usedRe), first check if the rx is empty
1016 // (and, if so, accept the input).
1017 if (d->origRe.pattern().isEmpty())
1018 return Acceptable;
1019
1020 const QRegularExpressionMatch m = d->usedRe.match(input, 0, QRegularExpression::PartialPreferCompleteMatch);
1021 if (m.hasMatch()) {
1022 return Acceptable;
1023 } else if (input.isEmpty() || m.hasPartialMatch()) {
1024 return Intermediate;
1025 } else {
1026 pos = input.size();
1027 return Invalid;
1028 }
1029}
1030
1031/*!
1032 \property QRegularExpressionValidator::regularExpression
1033 \brief the regular expression used for validation
1034
1035 By default, this property contains a regular expression with an empty
1036 pattern (which therefore matches any string).
1037*/
1038
1039QRegularExpression QRegularExpressionValidator::regularExpression() const
1040{
1041 Q_D(const QRegularExpressionValidator);
1042 return d->origRe;
1043}
1044
1045void QRegularExpressionValidator::setRegularExpression(const QRegularExpression &re)
1046{
1047 Q_D(QRegularExpressionValidator);
1048 d->setRegularExpression(re);
1049}
1050
1051/*!
1052 \internal
1053
1054 Sets \a re as the regular expression. It wraps the regexp that's actually used
1055 between \\A and \\z, therefore forcing an exact match.
1056*/
1057void QRegularExpressionValidatorPrivate::setRegularExpression(const QRegularExpression &re)
1058{
1059 Q_Q(QRegularExpressionValidator);
1060
1061 if (origRe != re) {
1062 usedRe = origRe = re; // copies also the pattern options
1063 usedRe.setPattern(QRegularExpression::anchoredPattern(re.pattern()));
1064 emit q->regularExpressionChanged(re);
1065 emit q->changed();
1066 }
1067}
1068
1069#endif // QT_CONFIG(regularexpression)
1070
1071QT_END_NAMESPACE
1072
1073#include "moc_qvalidator.cpp"
1074
1075#endif // QT_NO_VALIDATOR
void fixupWithLocale(QString &input, QLocaleData::NumberMode numMode, const QLocale &locale) const
#define LLONG_MAX
static qlonglong pow10(int exp)
static std::optional< QValidator::State > initialResultCheck(T min, T max, const QLocaleData::ParsingResult &result)
static int numDigits(qlonglong n)