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 bool hasMoreIntegerDigits(double value, double bound)
353{
354 if (value <= bound)
355 return false;
356 double factor = 10;
357 while (bound >= factor)
358 factor *= 10;
359 return value >= factor;
360}
361
362template <typename T> static inline
364 const QLocaleData::ParsingResult &result)
365{
366
367 using ParsingResult = QLocaleData::ParsingResult;
368 if (result.state == ParsingResult::Invalid)
369 return QValidator::Invalid;
370
371 const QLocaleData::CharBuff &buff = result.buff;
372 if (buff.isEmpty())
373 return QValidator::Intermediate;
374
375 char ch = buff[0];
376 const bool signConflicts = (min >= 0 && ch == '-') || (max < 0 && ch == '+');
377 if (signConflicts)
378 return QValidator::Invalid;
379
380 if (result.state == ParsingResult::Intermediate)
381 return QValidator::Intermediate;
382
383 return std::nullopt;
384}
385
386QValidator::State QIntValidator::validate(QString & input, int&) const
387{
388 QLocaleData::ParsingResult result =
389 locale().d->m_data->validateChars(input, QLocaleData::IntegerMode, -1,
390 locale().numberOptions());
391
392 std::optional<State> opt = initialResultCheck(b, t, result);
393 if (opt)
394 return *opt;
395
396 const QLocaleData::CharBuff &buff = result.buff;
397 QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(buff, 10);
398 if (!r.ok())
399 return Invalid;
400
401 qint64 entered = r.result;
402 if (entered >= b && entered <= t) {
403 bool ok = false;
404 locale().toInt(input, &ok);
405 return ok ? Acceptable : Intermediate;
406 }
407
408 if (entered >= 0) {
409 // the -entered < b condition is necessary to allow people to type
410 // the minus last (e.g. for right-to-left languages)
411 // The buffLength > tLength condition validates values consisting
412 // of a number of digits equal to or less than the max value as intermediate.
413
414 int buffLength = buff.size();
415 if (buff[0] == '+')
416 buffLength--;
417 const int tLength = t != 0 ? static_cast<int>(std::log10(qAbs(t))) + 1 : 1;
418
419 return (entered > t && -entered < b && buffLength > tLength) ? Invalid : Intermediate;
420 } else {
421 return (entered < b) ? Invalid : Intermediate;
422 }
423}
424
425/*! \reimp */
426void QIntValidator::fixup(QString &input) const
427{
428 auto [parseState, buff] =
429 locale().d->m_data->validateChars(input, QLocaleData::IntegerMode, -1,
430 locale().numberOptions());
431 if (parseState == QLocaleData::ParsingResult::Invalid)
432 return;
433
434 QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(buff, 10);
435 if (r.ok())
436 input = locale().toString(r.result);
437}
438
439/*!
440 Sets the range of the validator to only accept integers between \a
441 bottom and \a top inclusive.
442*/
443
444void QIntValidator::setRange(int bottom, int top)
445{
446 bool rangeChanged = false;
447 if (b != bottom) {
448 b = bottom;
449 rangeChanged = true;
450 emit bottomChanged(b);
451 }
452
453 if (t != top) {
454 t = top;
455 rangeChanged = true;
456 emit topChanged(t);
457 }
458
459 if (rangeChanged)
460 emit changed();
461}
462
463
464/*!
465 \property QIntValidator::bottom
466 \brief the validator's lowest acceptable value
467
468 By default, this property's value is derived from the lowest signed
469 integer available (-2147483648).
470
471 \sa setRange()
472*/
473void QIntValidator::setBottom(int bottom)
474{
475 setRange(bottom, top());
476}
477
478/*!
479 \property QIntValidator::top
480 \brief the validator's highest acceptable value
481
482 By default, this property's value is derived from the highest signed
483 integer available (2147483647).
484
485 \sa setRange()
486*/
487void QIntValidator::setTop(int top)
488{
489 setRange(bottom(), top);
490}
491
492/*!
493 \internal
494*/
495QValidator::QValidator(QObjectPrivate &d, QObject *parent)
496 : QObject(d, parent)
497{
498}
499
500/*!
501 \internal
502*/
503QValidator::QValidator(QValidatorPrivate &d, QObject *parent)
504 : QObject(d, parent)
505{
506}
507
508class QDoubleValidatorPrivate : public QValidatorPrivate
509{
510 Q_DECLARE_PUBLIC(QDoubleValidator)
511public:
517
519
521 void fixupWithLocale(QString &input, QLocaleData::NumberMode numMode,
522 const QLocale &locale) const;
523};
524
525
526/*!
527 \class QDoubleValidator
528
529 \brief The QDoubleValidator class provides range checking of
530 floating-point numbers.
531 \inmodule QtGui
532
533 QDoubleValidator provides an upper bound, a lower bound, and a
534 limit on the number of digits after the decimal point.
535
536 You can set the acceptable range in one call with setRange(), or
537 with setBottom() and setTop(). Set the number of decimal places
538 with setDecimals(). The validate() function returns the validation
539 state.
540
541 QDoubleValidator uses its locale() to interpret the number. For example,
542 in the German locale, "1,234" will be accepted as the fractional number
543 1.234. In Arabic locales, QDoubleValidator will accept Arabic digits.
544
545 \note The QLocale::NumberOptions set on the locale() also affect the way the
546 number is interpreted. For example, since QLocale::RejectGroupSeparator is
547 not set by default (except on the \c "C" locale), the validator will accept
548 group separators. If the string passes validation, pass it to
549 locale().toDouble() to obtain its numeric value.
550
551 \sa QIntValidator, QRegularExpressionValidator, QLocale::toDouble(), {Line Edits Example}
552*/
553
554 /*!
555 \enum QDoubleValidator::Notation
556 \since 4.3
557 This enum defines the allowed notations for entering a double.
558
559 \value StandardNotation The string is written in the standard format, a
560 whole number part optionally followed by a separator
561 and fractional part, for example \c{"0.015"}.
562
563 \value ScientificNotation The string is written in scientific form, which
564 optionally appends an exponent part to the
565 standard format, for example \c{"1.5E-2"}.
566
567 The whole number part may, as usual, include a sign. This, along with the
568 separators for fractional part, exponent and any digit-grouping, depend on
569 locale. QDoubleValidator doesn't check the placement (which would also
570 depend on locale) of any digit-grouping separators it finds, but it will
571 reject input that contains them if \l QLocale::RejectGroupSeparator is set
572 in \c locale().numberOptions().
573
574 \sa QLocale::numberOptions(), QLocale::decimalPoint(),
575 QLocale::exponential(), QLocale::negativeSign()
576*/
577
578/*!
579 Constructs a validator object with a \a parent object
580 that accepts any double.
581*/
582
583QDoubleValidator::QDoubleValidator(QObject *parent)
584 : QDoubleValidator(-HUGE_VAL, HUGE_VAL, -1, parent)
585{
586}
587
588
589/*!
590 Constructs a validator object with a \a parent object. This
591 validator will accept doubles from \a bottom to \a top inclusive,
592 with up to \a decimals digits after the decimal point.
593*/
594
595QDoubleValidator::QDoubleValidator(double bottom, double top, int decimals,
596 QObject * parent)
597 : QValidator(*new QDoubleValidatorPrivate , parent)
598{
599 b = bottom;
600 t = top;
601 dec = decimals;
602}
603
604
605/*!
606 Destroys the validator.
607*/
608
609QDoubleValidator::~QDoubleValidator()
610{
611}
612
613
614/*!
615 \fn QValidator::State QDoubleValidator::validate(QString &input, int &pos) const
616
617 Returns \l Acceptable if the string \a input is in the correct format and
618 contains a double within the valid range.
619
620 Returns \l Intermediate if \a input is in the wrong format or contains a
621 double outside the range.
622
623 Returns \l Invalid if the \a input doesn't represent a double or has too
624 many digits after the decimal point.
625
626 Note: If the valid range consists of just positive doubles (e.g. 0.0 to 100.0)
627 and \a input is a negative double then \l Invalid is returned. If notation()
628 is set to StandardNotation, and the input contains more digits before the
629 decimal point than a double in the valid range may have, \l Invalid is returned.
630 If notation() is ScientificNotation, and the input is not in the valid range,
631 \l Intermediate is returned. The value may yet become valid by changing the exponent.
632
633 By default, the \a pos parameter is not used by this validator.
634*/
635
636#ifndef LLONG_MAX
637# define LLONG_MAX Q_INT64_C(0x7fffffffffffffff)
638#endif
639
640QValidator::State QDoubleValidator::validate(QString & input, int &) const
641{
642 Q_D(const QDoubleValidator);
643
644 QLocaleData::NumberMode numMode = QLocaleData::DoubleStandardMode;
645 switch (d->notation) {
646 case StandardNotation:
647 numMode = QLocaleData::DoubleStandardMode;
648 break;
649 case ScientificNotation:
650 numMode = QLocaleData::DoubleScientificMode;
651 break;
652 }
653
654 return d->validateWithLocale(input, numMode, locale());
655}
656
657QValidator::State QDoubleValidatorPrivate::validateWithLocale(QString &input, QLocaleData::NumberMode numMode, const QLocale &locale) const
658{
659 Q_Q(const QDoubleValidator);
660 QLocaleData::ParsingResult result =
661 locale.d->m_data->validateChars(input, numMode, q->dec, locale.numberOptions());
662
663 std::optional<QValidator::State> opt = initialResultCheck(q->b, q->t, result);
664 if (opt)
665 return *opt;
666
667 bool ok = false;
668 double i = locale.toDouble(input, &ok); // returns 0.0 if !ok
669 Q_ASSERT(!qIsNaN(i)); // Would be caught by validateChars()
670 if (!ok)
671 return QValidator::Intermediate;
672
673 if (i >= q->b && i <= q->t)
674 return QValidator::Acceptable;
675
676 if (notation == QDoubleValidator::StandardNotation) {
677 const double max = qMax(qAbs(q->b), qAbs(q->t));
678 if (hasMoreIntegerDigits(qAbs(i), max))
679 return QValidator::Invalid;
680 }
681
682 return QValidator::Intermediate;
683}
684
685/*!
686 \since 6.3
687 \overload
688
689 Attempts to fix the \a input string to an \l Acceptable representation of a
690 double.
691
692 The format of the number is determined by \l notation(), \l decimals(),
693 \l locale() and the latter's \l {QLocale::}{numberOptions()}.
694
695 To comply with \l notation(), when \l ScientificNotation is used, the fixed
696 value will be represented in its normalized form, which means that any
697 non-zero value will have one non-zero digit before the decimal point.
698
699 \snippet code/src_gui_util_qvalidator.cpp 7
700
701 To comply with \l decimals(), when it is \c {-1} the number of digits used
702 will be determined by \l QLocale::FloatingPointShortest. Otherwise, the
703 fractional part of the number is truncated (with rounding, as appropriate)
704 if its length exceeds \l decimals(). When \l notation() is
705 \l ScientificNotation this is done after the number has been put into its
706 normalized form.
707
708 \snippet code/src_gui_util_qvalidator.cpp 8
709
710 \note If \l decimals() is set to, and the string provides, more than
711 \c {std::numeric_limits<double>::digits10}, digits beyond that many in the
712 fractional part may be changed. The resulting string shall encode the same
713 floating-point number, when parsed to a \c double.
714*/
715void QDoubleValidator::fixup(QString &input) const
716{
717 Q_D(const QDoubleValidator);
718 const auto numberMode = d->notation == StandardNotation ? QLocaleData::DoubleStandardMode
719 : QLocaleData::DoubleScientificMode;
720
721 d->fixupWithLocale(input, numberMode, locale());
722}
723
724void QDoubleValidatorPrivate::fixupWithLocale(QString &input, QLocaleData::NumberMode numMode,
725 const QLocale &locale) const
726{
727 Q_Q(const QDoubleValidator);
728 // Passing -1 as the number of decimals, because fixup() exists to improve
729 // an Intermediate value, if it can.
730 auto [parseState, buff] =
731 locale.d->m_data->validateChars(input, numMode, -1, locale.numberOptions());
732 if (parseState == QLocaleData::ParsingResult::Invalid)
733 return;
734
735 // buff contains data in C locale.
736 bool ok = false;
737 const double entered = QByteArrayView(buff).toDouble(&ok);
738 if (ok) {
739 // Here we need to adjust the output format accordingly
740 char mode;
741 if (numMode == QLocaleData::DoubleStandardMode) {
742 mode = 'f';
743 } else {
744 // Scientific mode can be either 'e' or 'E'
745 const QString exp = locale.exponential();
746 bool preferUpper = false;
747 QStringIterator scan(exp);
748 while (!preferUpper && scan.hasNext()) {
749 const char32_t ch = scan.next();
750 if (QChar::isUpper(ch))
751 preferUpper = true;
752 }
753 if (preferUpper)
754 mode = input.contains(exp.toLower()) ? 'e' : 'E';
755 else // If case-free, we don't care which we use; otherwise, prefer lower.
756 mode = input.contains(exp.toUpper()) ? 'E' : 'e';
757 }
758 int precision;
759 if (q->dec < 0) {
760 precision = QLocale::FloatingPointShortest;
761 } else {
762 if (mode == 'f') {
763 const auto decimalPointIndex = buff.indexOf('.');
764 precision = decimalPointIndex >= 0 ? buff.size() - decimalPointIndex - 1 : 0;
765 } else {
766 auto eIndex = buff.indexOf('e');
767 // No need to check for 'E' because we can get only 'e' after a
768 // call to validateChars()
769 if (eIndex < 0)
770 eIndex = buff.size();
771 precision = eIndex - (buff.contains('.') ? 1 : 0)
772 - (buff[0] == '-' || buff[0] == '+' ? 1 : 0);
773 }
774 // Use q->dec to limit the number of decimals, because we want the
775 // fixup() result to pass validate().
776 precision = qMin(precision, q->dec);
777 }
778 input = locale.toString(entered, mode, precision);
779 }
780}
781
782/*!
783 Sets the validator to accept doubles from \a minimum to \a maximum
784 inclusive, with at most \a decimals digits after the decimal
785 point.
786
787 \note Setting the number of decimals to -1 effectively sets it to unlimited.
788 This is also the value used by a default-constructed validator.
789*/
790
791void QDoubleValidator::setRange(double minimum, double maximum, int decimals)
792{
793 bool rangeChanged = false;
794 if (b != minimum) {
795 b = minimum;
796 rangeChanged = true;
797 emit bottomChanged(b);
798 }
799
800 if (t != maximum) {
801 t = maximum;
802 rangeChanged = true;
803 emit topChanged(t);
804 }
805
806 if (dec != decimals) {
807 dec = decimals;
808 rangeChanged = true;
809 emit decimalsChanged(dec);
810 }
811 if (rangeChanged)
812 emit changed();
813}
814
815/*!
816 \overload
817
818 Sets the validator to accept doubles from \a minimum to \a maximum
819 inclusive without changing the number of digits after the decimal point.
820*/
821void QDoubleValidator::setRange(double minimum, double maximum)
822{
823 setRange(minimum, maximum, decimals());
824}
825
826/*!
827 \property QDoubleValidator::bottom
828 \brief the validator's minimum acceptable value
829
830 By default, this property contains a value of -infinity.
831
832 \sa setRange()
833*/
834
835void QDoubleValidator::setBottom(double bottom)
836{
837 setRange(bottom, top(), decimals());
838}
839
840
841/*!
842 \property QDoubleValidator::top
843 \brief the validator's maximum acceptable value
844
845 By default, this property contains a value of infinity.
846
847 \sa setRange()
848*/
849
850void QDoubleValidator::setTop(double top)
851{
852 setRange(bottom(), top, decimals());
853}
854
855/*!
856 \property QDoubleValidator::decimals
857 \brief the validator's maximum number of digits after the decimal point
858
859 By default, this property contains a value of -1, which means any number
860 of digits is accepted.
861
862 \sa setRange()
863*/
864
865void QDoubleValidator::setDecimals(int decimals)
866{
867 setRange(bottom(), top(), decimals);
868}
869
870/*!
871 \property QDoubleValidator::notation
872 \since 4.3
873 \brief the notation of how a string can describe a number
874
875 By default, this property is set to ScientificNotation.
876
877 \sa Notation
878*/
879
880void QDoubleValidator::setNotation(Notation newNotation)
881{
882 Q_D(QDoubleValidator);
883 if (d->notation != newNotation) {
884 d->notation = newNotation;
885 emit notationChanged(d->notation);
886 emit changed();
887 }
888}
889
890QDoubleValidator::Notation QDoubleValidator::notation() const
891{
892 Q_D(const QDoubleValidator);
893 return d->notation;
894}
895
896#if QT_CONFIG(regularexpression)
897
898/*!
899 \class QRegularExpressionValidator
900 \inmodule QtGui
901 \brief The QRegularExpressionValidator class is used to check a string
902 against a regular expression.
903
904 \since 5.1
905
906 QRegularExpressionValidator uses a regular expression (regexp) to
907 determine whether an input string is \l Acceptable, \l
908 Intermediate, or \l Invalid. The regexp can either be supplied
909 when the QRegularExpressionValidator is constructed, or at a later time.
910
911 If the regexp partially matches against the string, the result is
912 considered \l Intermediate. For example, "" and "A" are \l Intermediate for
913 the regexp \b{[A-Z][0-9]} (whereas "_" would be \l Invalid).
914
915 QRegularExpressionValidator automatically wraps the regular expression in
916 the \c{\\A} and \c{\\z} anchors; in other words, it always attempts to do
917 an exact match.
918
919 Example of use:
920 \snippet code/src_gui_util_qvalidator.cpp 5
921
922 Below we present some examples of validators. In practice they would
923 normally be associated with a widget as in the example above.
924
925 \snippet code/src_gui_util_qvalidator.cpp 6
926
927 \sa QRegularExpression, QIntValidator, QDoubleValidator
928*/
929
930class QRegularExpressionValidatorPrivate : public QValidatorPrivate
931{
932 Q_DECLARE_PUBLIC(QRegularExpressionValidator)
933
934public:
935 QRegularExpression origRe; // the one set by the user
936 QRegularExpression usedRe; // the one actually used
937 void setRegularExpression(const QRegularExpression &re);
938};
939
940/*!
941 Constructs a validator with a \a parent object that accepts
942 any string (including an empty one) as valid.
943*/
944
945QRegularExpressionValidator::QRegularExpressionValidator(QObject *parent)
946 : QValidator(*new QRegularExpressionValidatorPrivate, parent)
947{
948 // origRe in the private will be an empty QRegularExpression,
949 // and therefore this validator will match any string.
950}
951
952/*!
953 Constructs a validator with a \a parent object that
954 accepts all strings that match the regular expression \a re.
955*/
956
957QRegularExpressionValidator::QRegularExpressionValidator(const QRegularExpression &re, QObject *parent)
958 : QRegularExpressionValidator(parent)
959{
960 Q_D(QRegularExpressionValidator);
961 d->setRegularExpression(re);
962}
963
964
965/*!
966 Destroys the validator.
967*/
968
969QRegularExpressionValidator::~QRegularExpressionValidator()
970{
971}
972
973/*!
974 Returns \l Acceptable if \a input is matched by the regular expression for
975 this validator, \l Intermediate if it has matched partially (i.e. could be
976 a valid match if additional valid characters are added), and \l Invalid if
977 \a input is not matched.
978
979 In case the \a input is not matched, the \a pos parameter is set to
980 the length of the \a input parameter; otherwise, it is not modified.
981
982 For example, if the regular expression is \b{\\w\\d\\d} (word-character,
983 digit, digit) then "A57" is \l Acceptable, "E5" is \l Intermediate, and
984 "+9" is \l Invalid.
985
986 \sa QRegularExpression::match()
987*/
988
989QValidator::State QRegularExpressionValidator::validate(QString &input, int &pos) const
990{
991 Q_D(const QRegularExpressionValidator);
992
993 // We want a validator with an empty QRegularExpression to match anything;
994 // since we're going to do an exact match (by using d->usedRe), first check if the rx is empty
995 // (and, if so, accept the input).
996 if (d->origRe.pattern().isEmpty())
997 return Acceptable;
998
999 const QRegularExpressionMatch m = d->usedRe.match(input, 0, QRegularExpression::PartialPreferCompleteMatch);
1000 if (m.hasMatch()) {
1001 return Acceptable;
1002 } else if (input.isEmpty() || m.hasPartialMatch()) {
1003 return Intermediate;
1004 } else {
1005 pos = input.size();
1006 return Invalid;
1007 }
1008}
1009
1010/*!
1011 \property QRegularExpressionValidator::regularExpression
1012 \brief the regular expression used for validation
1013
1014 By default, this property contains a regular expression with an empty
1015 pattern (which therefore matches any string).
1016*/
1017
1018QRegularExpression QRegularExpressionValidator::regularExpression() const
1019{
1020 Q_D(const QRegularExpressionValidator);
1021 return d->origRe;
1022}
1023
1024void QRegularExpressionValidator::setRegularExpression(const QRegularExpression &re)
1025{
1026 Q_D(QRegularExpressionValidator);
1027 d->setRegularExpression(re);
1028}
1029
1030/*!
1031 \internal
1032
1033 Sets \a re as the regular expression. It wraps the regexp that's actually used
1034 between \\A and \\z, therefore forcing an exact match.
1035*/
1036void QRegularExpressionValidatorPrivate::setRegularExpression(const QRegularExpression &re)
1037{
1038 Q_Q(QRegularExpressionValidator);
1039
1040 if (origRe != re) {
1041 usedRe = origRe = re; // copies also the pattern options
1042 usedRe.setPattern(QRegularExpression::anchoredPattern(re.pattern()));
1043 emit q->regularExpressionChanged(re);
1044 emit q->changed();
1045 }
1046}
1047
1048#endif // QT_CONFIG(regularexpression)
1049
1050QT_END_NAMESPACE
1051
1052#include "moc_qvalidator.cpp"
1053
1054#endif // QT_NO_VALIDATOR
void fixupWithLocale(QString &input, QLocaleData::NumberMode numMode, const QLocale &locale) const
#define LLONG_MAX
static std::optional< QValidator::State > initialResultCheck(T min, T max, const QLocaleData::ParsingResult &result)
static bool hasMoreIntegerDigits(double value, double bound)