You are on page 1of 7

Input Validation and

Regular Expressions
COS3711 - e-Tutor
Tutor Powerpoint Ch 14

Outline
Input Masks
Validators
Regular Expressions

Input Marks
Control what is typed in an input widget by the user
A QLineEdit object provides a Mask for the input
A mask is a special string that tells the line edit what type of
characters the user can type next. If a user types a character that is
not in range, it is simply ignored by the line edit.
A mask has both normal characters and special character.
character
The following code creates a QLineEdit that takes a numeric value in
the form: 1234-123-1234-123
123 (four digits, then a dash, then 3 digits,
another dash, four more digits, a dash and end with 3 digits):

Input Masks (Cont.)


#include <Application>
#include <qlineedit.h>
int main(int argc, char *argv[]){
QApplication app(argc, argv);
QLineEdit e;
e.setInputMask("9999-999-9999-999");
999");
e.show();
return app.exec();
}

Masks are useful for inputs with rigid formats such as IP addresses
and serial numbers. For more complex inputs,
inputs a more flexible
solution is needed: validators.

Validators
Objects that can be attached to input widgets such as QLineEdit,
QComboBox, and QSpinBox to validate user input
Implemented with the QValidator class
QValidator class provides three important subclasses QIntValidator,
QDoubleValidator and QRegExpValidator for input validation
QIntValidator - validates integer values,
QDoubleValidator - validates floating point values and
QRegExpValidator - validates any text using regular expression
The following code creates an integer only line edit using a validator,
i.e., an example of use of QIntValidator

Validators (Cont.)
#include <QApplication>
#include <qlineedit.h>
#include <QIntValidator>
int main(int argc, char *argv[]){
QApplication app(argc, argv);
QLineEdit e;
QIntValidator *v = new QIntValidator(0,
(0, 100);
100
e.setValidator( v );//a QIntValidator is set a validator in a QLineEdit
e.show();
return app.exec();
}

The above code implements a line edit that allows only integers between
0 and 100.

Validators (Cont.)
QRegExpValidator is a flexible validator
QRegExpValidator accepts a regular expression and use it to validate any input text in a
QLineEdit
The following code implements a QLineEdit that accepts only valid names
#include <QApplication>
int main(int argc, char *argv[]){
QApplication app(argc, argv);
QLineEdit e;
QRegExp re("[_a-zA-Z][_a-zA-Z0-9]+");
QRegExpValidator
QRegExpValidator *v = new QRegExpValidator(re);
e.setValidator( v );
e.show();
return app.exec();
}

You might also like