axyd icon

Email Validator

axyd | PRO | 05/27/20 11:08:15 AM UTC | 0 ⭐ | 2554 👁️ | Never ⏰ | []
C++ |

1.7 KB

|

None

|

0 👍

/

0 👎

/*Rennex helped*/
 
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include "stdio.h"  //strtok
 
using namespace std;
 
bool validateEmail(string);
 
int main(){
    string email;
    bool isValid;
 
    do{
        cout<< " Enter email (or q/Q to quit): ";
        getline(cin, email);
        isValid= validateEmail(email);
 
        if(isValid)
            cout<< "\n\t Valid Email\n";
        else
            cout<< "\n\tInvalid Email\n";
        
    } while (email != "q" && email != "Q");
 
    return 0;
}
 
bool validateEmail(string email){
 
    //check name exists (first character is alphanumeric)
    //check last character valid (alphanumeric)
    if(!isalnum(email.at(0)) || !isalnum(email.at(email.size()-1))){
        cout<<"\n\tINVALID NAME\n";
        return false;
    }
 
    //check if @ used multiple times
    int atPos= 0;
 
    for(int ctr= 0; ctr != email.size(); ++ctr){ 
        if(atPos != 0){
            cout<< "\n\t'@' used multiple times";
            return false;
        }
    }
 
    //split into sections
    vector<string> vData;
 
    char str[321];
    strcpy(str, email.c_str()); //convert to cstring
 
    char *pch;
    pch= strtok(str,"@.");    //first part until delimiter
    vData.push_back(pch);
 
    while(pch != NULL){         //each successive delimiter
        pch= strtok (NULL, "@.");
        if(pch == NULL) break;
        
        vData.push_back(pch);
    }
 
    if(vData.size() <3){    //make sure at least 3 parts exist (name, domain, tld)...but can have more than 3 EX: subdomains
        cout << "\n\tNot enough sections ([email protected])";
        return false;
    }
 
    return true;
}

Comments