Input Validation

Process of checking user input against specified criteria.

 

Two types:

  • String
    • Accept all user input as a string, then accept/reject that string based on its format
  • Numerical
    • Accept/reject user entered value ┬áis within a specified range

 

The cctype header file provides the following member functions:

 

Function Meaning
isalnum(int) Returns non-zero if the parameter is a letter or a digit
isalpha(int) Returns non-zero if the parameter is a letter
iscntrl(int) Returns non-zero if the parameter is a control character
isdigit(int) Returns non-zero if the parameter is a digit
isgraph(int) Returns non-zero if the parameter is printable character that is not whitespace
isprint(int) Returns non-zero if the parameter is printable character (including whitespace)
ispunct(int) Returns non-zero if the parameter is neither alphanumeric nor whitespace
isspace(int) Returns non-zero if the parameter is whitespace
isxdigit(int) Returns non-zero if the parameter is a hexadecimal digit (0-9, a-f, A-F)

 

 

String Validation

 

This example asks the user to enter their name and checks the string for alpha or space characters, or set the reject boolean if not:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main () {

	cout << "Please enter name:" << endl ;
	string userName ;
	getline(cin, userName) ;

	bool rejected = false ; //set a boolean to check against

	for (unsigned int i = 0; i < userName.length() && !rejected ; i++) {

		if (isalpha(userName[i])) //check for alpha characters
			continue;

		if (userName[i] == ' ') //check for spaces
			continue;

		rejected = true ; //set rejected if anything apart from alpha or space characters
	}

	if (!rejected){
		cout << "Thanks for entering only alpha and/or spaces" << endl ;
	} else {
		cout << "Next time please don't enter numbers or punctuation." << endl ;
	}

	return 0;
}

Compile & Run:

Please enter name:
Derrick
Thanks for entering only alpha and/or spaces

 

 

Numeric Validation

 

This example asks the user to enter their birth year and checks the number entered via the stream extractor to see if it falls with the specified range:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main () {
	int birthYear;

	while (true) {
	cout << "Please enter the year you were born in:" << endl ;

	cin >> birthYear;

	if (cin.fail()) { //no data entered

		cin.clear() ; //reset state bits
		cin.ignore(1000, '\n') ; //clear out bad stream input
		continue ;
	}

	if (birthYear < 1900  && birthYear > 2013) //make sure birthYear is realistic
		continue ;

	break ;
	}

	cout << "Thanks! You must be about " << 2013 - birthYear << " years old now!" << endl ;

	return 0;
}

Compile & Run:

Please enter the year you were born in:
1970
Thanks! You must be about 43 years old now!

Leave a Reply