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

source code of qtbase/src/gui/util/qvalidator.cpp