BOOL CDataValidator::IsValidEmail(const CString& strEmail, int nMaxLen, CString& strError )
{
if( strEmail.IsEmpty() )
{
strError = "Email地址中不能为空!";
return false;
}
else if( strEmail.GetLength() >= 40 )
{
strError = "Email地址中长度不能超过40个字符!";
return false;
}
char szEmail[64] = {'\0'};
strncpy( szEmail, strEmail,64 );
char* P=NULL;
char* strempt = szEmail;
int nDotCount = 0;
int nAtCount = 0;
for( P = strempt; *P != '\0';P++)
{
if(*P == ' ')
{
strError = "Email地址中不能有空字符!";
return FALSE;
}
else if((((*P >= 48)&&(*P <= 57))||((*P >= 64)&&(*P <= 90))||((*P >= 97)&&(*P <= 122))||*P==45||*P=='.'||*P==95)== 0)
{
strError = "Email地址只能由字母、数字、下划线、\"@\"以及\".\"字符组成!";
return FALSE;
}
else if(*P == '.')
++nDotCount;
else if(*P == '@')
++nAtCount;
}
if(nAtCount >1 || nAtCount ==0 )
{
strError = "Email地址中\"@\"字符有且只能有一个!";
return FALSE;
}
if( nDotCount>1 || nDotCount==0 )
{
strError = "Email地址中\".\"字符有且只能有一个!";
return FALSE;
}
int nIndexAt = strEmail.ReverseFind('@');
if( nIndexAt == 0 )
{
strError = "Email地址中\"@\"字符之前至少包含一个字符!";
return FALSE;
}
int nIndex2 = strEmail.ReverseFind('.');
if ( (nIndex2-nIndexAt)<0 )
{
strError = "Email地址中字符\".\"的位置不能在字符\"@\"之前!";
return FALSE;
}
else if ( (nIndex2-nIndexAt)<= 1)
{
strError = "Email地址中字符\"@\"和\".\"字符之间至少包含一个字符"!;
return FALSE;
}
int nIndexUnl = strEmail.ReverseFind('_');
if( nIndexUnl >= nIndexAt )
{
strError = "Email地址中字符\"@\"的后面不能有\"_\"字符!";
return FALSE;
}
return TRUE;
}
转载于:https://blog.51cto.com/machh85/1050293