Home > Win32/MFC > Simple CEdit Validation

Simple CEdit Validation

June 27th, 2007

Sometime you need some CEdit Validation, for example, restricting the data number only.

The simple implemetion is to handle the EN_UPDATE notification message. The EN_UPDATE message is useful to handle as it caters for both normal entry and clipboard paste. You can do that in the Dialog or subclass the CEdit class.

Here is an example of a derived CEdit class.

class CNumEdit : public CEdit
{
//….
    
afx_msg void OnUpdate();
    
//}}AFX_MSG
 
    
DECLARE_MESSAGE_MAP()
private:
    
CString m_strLastGood;
};

In the cpp file:

BEGIN_MESSAGE_MAP(CNumEdit, CEdit)
    
//{{AFX_MSG_MAP(CNumEdit)
    
ON_CONTROL_REFLECT(EN_UPDATE, OnUpdate)
    
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
void CNumEdit::OnUpdate()
{
    
CString str;
    
GetWindowText( str );
    
bool bProblem = false;
    
for ( int indx = 0; indx < str.GetLength(); indx++ )
    
{
        
if (( str[indx] < ‘0) || ( str[indx] > ‘9) )
        
{
            
bProblem = true;
            
break;
        
}
    
}
    
if ( bProblem )
    
{
        
int start, end;
        
/* Find the current caret position */
        
GetSel( start, end );
        
/* Restore the last good text that was entered */
        
SetWindowText( m_strLastGood );
        
/* Restore the caret */
        
SetSel( start-1, end-1, true );
        
/* Let the user know */
        
MessageBeep( MB_OK );
    
}
    
else
    
{
    
/* Store the last good entry string in a member variable of the Hex edit class*/
        
m_strLastGood = str;
    
}     
}

At last, you may find one of these meets your needs:

  • http://www.codeproject.com/editctrl/maskededit.asp
  • http://www.codeproject.com/editctrl/validatingedit.asp

Win32/MFC , ,

  1. No comments yet.
  1. No trackbacks yet.