tags:

views:

73

answers:

2

VC++ 6.0, MFC application

In CEditBox (IDC_EDIT1) I have created a CString variable (m_strEdit1). How do I validate that the input is a number, including sign (+ and -)? eg: (+10, -56)

It should not accept alphanumeric characters. How can I do this?

A: 

Have a look at CString::SpanIncluding?

Jonas Gulle
i want to enter only numbers not characters please give me the one example thanks in advance
A: 

You should probably do this by validating the characters as they're entered:


class CEditBox public CEdit
{
    afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
    DECLARE_MESSAGE_MAP()
};


BEGIN_MESSAGE_MAP(CEditBox, CEdit)
    ON_WM_CHAR()
END_MESSAGE_MAP()

void CEditBox::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // quick validation
    if (nChar != _T('+') && nChar != _T('-') && !isdigit(nChar))
        return;

    CString strText;
    GetWindowText(strText);

    int nStartChar;
    int nEndChar;
    GetSel(nStartChar, nEndChar);

    CString strNewText = strText.Left(nStartChar) + 
                         nChar + 
                         strText.Right(strText.GetLength() - nEndChar);

    CString strFirst = strNewText.Left(1);

    // is first character valid?
    if (strFirst != _T("+") && strFirst != _T("-") && && !isdigit(strFirst[0]))
        return;

    CString strSecond = strNewText.Mid(1);

    // are remaining characters all digits? (ie no more + or -)
    for (int i = 0; i < strSecond.GetLength(); ++i)
    {
        if (!isdigit(strSecond[i]))
            return;
    }

    CEdit::OnChar(nChar, nRepCnt, nFlags);
}
Alan