Source of data_validation.cpp


  1: //data_validation.cpp (based on a Deitel example)
  2: //Validating user input with regular expressions.

  4: #include <iostream>
  5: #include <string>
  6: using namespace std;

  8: #include "boost/regex.hpp"
  9: using boost::regex;
 10: using boost::regex_match;

 12: //Validate the data format using a regular expression
 13: bool isValid
 14: (
 15:      const string& data,      //in
 16:      const string& expression //in
 17: );

 19: //Collect input from the user
 20: string inputData
 21: (
 22:     const string& fieldName, //in
 23:     const string& expression //in
 24: );

 26: int main()
 27: {
 28:     cout << endl;

 30:     //Enter last name
 31:     string lastName = inputData("last name", "[A-Z][a-zA-Z]*");

 33:     //Enter first name
 34:     string firstName = inputData("first name", "[A-Z][a-zA-Z]*");

 36:     //Enter address
 37:     string address = inputData("address", 
 38:         "[0-9]+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");

 40:     //Enter city
 41:     string city = 
 42:         inputData("city", "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");

 44:     //Enter state
 45:     string province = inputData("province",
 46:         "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");

 48:     //Enter postal code
 49:     string postalCode = inputData("postal code",
 50:         "[A-Z]\\d[A-Z] \\d[A-Z]\\d");

 52:     //Enter phone number
 53:     string phoneNumber = inputData("phone number (xxx-xxx-xxxx)", 
 54:         "[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");

 56:     //Display the validated data
 57:     cout << "\nValidated Data\n"
 58:         << "\nLast name ...... " << lastName
 59:         << "\nFirst name ..... " << firstName
 60:         << "\nAddress ........ " << address
 61:         << "\nCity ........... " << city
 62:         << "\nState .......... " << province
 63:         << "\nPostal code .... " << postalCode
 64:         << "\nPhone number ... " << phoneNumber << endl;
 65:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 66: }

 68: bool isValid
 69: (
 70:      const string& data,      //in
 71:      const string& expression //in
 72: )
 73: {
 74:     //Create a regex to validate the data
 75:     regex validationExpression = regex(expression);
 76:     return regex_match(data, validationExpression);
 77: }

 79: string inputData
 80: (
 81:     const string& fieldName, //in
 82:     const string& expression //in
 83: )
 84: {
 85:     string data; //For storing data entered by the user

 87:     //Request the data from the user
 88:     cout << "Enter " << fieldName << ": ";
 89:     getline(cin, data);

 91:     //Validate the data and ask again if invalid
 92:     while (!isValid(data, expression))
 93:     {
 94:         cout << "Invalid " << fieldName << ".\n";
 95:         cout << "Enter " << fieldName << ": ";
 96:         getline(cin, data);
 97:     }
 98:     return data;
 99: }