Advertisement
axyd

Email Validator

May 27th, 2020
2,129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. /*Rennex helped*/
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <cstring>
  6. #include <string>
  7. #include "stdio.h"  //strtok
  8.  
  9. using namespace std;
  10.  
  11. bool validateEmail(string);
  12.  
  13. int main(){
  14.     string email;
  15.     bool isValid;
  16.  
  17.     do{
  18.         cout<< " Enter email (or q/Q to quit): ";
  19.         getline(cin, email);
  20.         isValid= validateEmail(email);
  21.  
  22.         if(isValid)
  23.             cout<< "\n\t Valid Email\n";
  24.         else
  25.             cout<< "\n\tInvalid Email\n";
  26.        
  27.     } while (email != "q" && email != "Q");
  28.  
  29.     return 0;
  30. }
  31.  
  32. bool validateEmail(string email){
  33.  
  34.     //check name exists (first character is alphanumeric)
  35.     //check last character valid (alphanumeric)
  36.     if(!isalnum(email.at(0)) || !isalnum(email.at(email.size()-1))){
  37.         cout<<"\n\tINVALID NAME\n";
  38.         return false;
  39.     }
  40.  
  41.     //check if @ used multiple times
  42.     int atPos= 0;
  43.  
  44.     for(int ctr= 0; ctr != email.size(); ++ctr){
  45.         if(atPos != 0){
  46.             cout<< "\n\t'@' used multiple times";
  47.             return false;
  48.         }
  49.     }
  50.  
  51.     //split into sections
  52.     vector<string> vData;
  53.  
  54.     char str[321];
  55.     strcpy(str, email.c_str()); //convert to cstring
  56.  
  57.     char *pch;
  58.     pch= strtok(str,"@.");    //first part until delimiter
  59.     vData.push_back(pch);
  60.  
  61.     while(pch != NULL){         //each successive delimiter
  62.         pch= strtok (NULL, "@.");
  63.         if(pch == NULL) break;
  64.        
  65.         vData.push_back(pch);
  66.     }
  67.  
  68.     if(vData.size() <3){    //make sure at least 3 parts exist (name, domain, tld)...but can have more than 3 EX: subdomains
  69.         cout << "\n\tNot enough sections (name@domain.tld)";
  70.         return false;
  71.     }
  72.  
  73.     return true;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement