Click here to Skip to main content
15,886,078 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I want to check if a CString variable contains only numbers and the character: "/". I used the FindOneOf function but that doesn't work.

C++
CString startDate; 
if ( startDate.FindOneOf(_T("abcdefghijklmnopqrstuvwxyz")) == true )



Is there a better way to do this? The date format is "dd/mm/yyyy"
Posted

You may write a short parser that checks each character:
LPCTSTR lpszParse = strDate.GetString();
while (*lpszParse && _tcschr(lpszParse, _T("01234567890/")))
    lpszParse++;
if (*lpszParse == _T('\0') && !strDate.IsEmpty())
{
    // valid string
}

But with a fixed date format you may also parse it completely to check for a valid date:
C++
int nDay = _tstoi(strDate.GetString());
int nMonth = _tstoi(strDate.GetString() + 3);
int nYear = _tstoi(strDate.GetString() + 6);
if (strDate.GetAt(2) == _T('/') &&
    strDate.GetAt(5) == _T('/') &&
//  strDate.GetLength() == 10 &&
    nDay >= 1 && nDay <= 31 &&
    nMonth >= 1 && nMOnth <= 12)
{
// valid
}
 
Share this answer
 
Comments
Sumal.V 7-Sep-12 11:36am    
Thanks a ton! That works :)
Are you using MFC?

This might work:

C++
CString startDate = "01/12/2012";
COleDateTime date;
if (date.ParseDateTime (startDate, VAR_DATEVALUEONLY)) 
{ 
    // Parse succeeded, so it's a valid date
}
 
Share this answer
 
Comments
Sumal.V 7-Sep-12 11:36am    
Yeah I use Visual C++. But this didn't work ! But hey Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900