Click here to Skip to main content
15,860,844 members
Articles / Desktop Programming / MFC
Article

Use wildcard to compare string and validate input

Rate me:
Please Sign up or sign in to vote.
3.89/5 (8 votes)
3 Feb 20051 min read 57.2K   13   8
This article describes how to use wildcard to make input validation in CEdit control or to compare string with wildcard.

Introduction

This article was inspired by Jack Handy (Wildcard string compare).

It describes a function to compare strings with wildcards. I have modified Jack's function to use MFC and use optional character in the wildcard string.

Wildcard sample

If you want to check a string like 'test' or 'tet', you may use the wildcard like this : te^st where ^ indicates an optional char.

I included another parameter to limit characters used in wildcard * or ?.

C++
if (WildMatch("^-*?^.*", sValue, "0123456789")) {
    MessageBox("OK you have a real");
} else {
    MessageBox("Not a real");
}

This sample validates the string in sValue has a good format to be a real number.

Function code

C++
BOOL WildMatch(CString sWild, CString sString, CString sLimitChar)
{
    BOOL bAny = FALSE;
    BOOL bNextIsOptional = FALSE;
    BOOL bAutorizedChar = TRUE;

    int i=0;
    int j=0;

    // Check all the string char by char
    while (i<sString.GetLength()) 
    {
      // Check index for array overflow
      if (j<sWild.GetLength())
      {
          // Manage '*' in the wildcard
          if (sWild[j]=='*') 
          {
          // Go to next character in the wildcard
          j++;

          // Enf of the string and wildcard end 
          // with *, only test string validity
          if (j>=sWild.GetLength()) 
          {
          // Check end of the string
          while (!sLimitChar.IsEmpty() && i<sString.GetLength()) 
          {
          // If this char is not ok, return false
          if (sLimitChar.Find(sString[i])<0)
              return FALSE;

          i++;
          }

          return TRUE;
          }

          bAny = TRUE;
          bNextIsOptional = FALSE;
          } 
          else 
          {
              // Optional char in the wildcard
              if (sWild[j]=='^')
              {
              // Go to next char in the wildcard and indicate 
              // that the next is optional
              j++;
 
              bNextIsOptional = TRUE;
              }
              else
              {
                bAutorizedChar = 
                  ((sLimitChar.IsEmpty()) || (sLimitChar.Find(sString[i])>=0));

                // IF :
                  if (// Current char match the wildcard
                    sWild[j] == sString[i] 
                    // '?' is used and current char is in autorized char list
                    || (sWild[j] == '?' && bAutorizedChar)
                    // Char is optional and it's not in the string
                    // and it's necessary to test if '*' make any 
                    // char browsing
                    || (bNextIsOptional && !(bAny && bAutorizedChar))) 
                    {
                    // If current char match wildcard, 
                    // we stop for any char browsing
                    if (sWild[j] == sString[i])
                        bAny = FALSE;

                    // If it's not an optional char who is not present,
                    // go to next
                    if (sWild[j] == sString[i] || sWild[j] == '?')
                        i++;

                    j++;

                    bNextIsOptional = FALSE;
                    } 
                    else
                    // If we are in any char browsing ('*') 
                    // and curent char is autorized
                    if (bAny && bAutorizedChar)
                        // Go to next
                        i++;
                    else
                        return FALSE;
               }
            }
        }
        else
        // End of the wildcard but not the 
        // end of the string => 
        // not matching
        return FALSE;
    }

    if (j<sWild.GetLength() && sWild[j]=='^')
    {
        bNextIsOptional = TRUE;
        j++;
    }


    // If the string is shorter than wildcard 
    // we test end of the 
    // wildcard to check matching
    while ((j<sWild.GetLength() && sWild[j]=='*') || bNextIsOptional)
    {
        j++;
        bNextIsOptional = FALSE;

        if (j<sWild.GetLength() && sWild[j]=='^')
        {
            bNextIsOptional = TRUE;
            j++;
        }
    }

    return j>=sWild.GetLength();
}

CEdit input validation

This sample shows you how to use this function to control input validation in a dynamic way.

Be careful when you define your wildcard, because it must be always true! If you want more advanced testing, don't test in real time but do only when the user validates.

For example, if you use ^-?*^.*, the user can never put the minus sign first, because '?' specifies one char is always necessary!

You can put this code in the OnChar of your CEdit child class, or if you don't want to derive a new class, you can put it in the PreTranslateMessage of the mother window, like:

C++
if (pMsg->message==WM_CHAR && pMsg->hwnd==pEdit->m_hWnd && 
         pMsg->wParam>=32)
{
    // Define parameters
    CString sSaveText="";
    CString sNewText="";
    CString sLimitChar="0123456789";
    CString sWildCard="^-*^.*";
    int iNbMaxChar = 10;

        // If we use only upper case, makeupper
    if (m_bMakeUpper)
        pMsg->wParam = toupper(pMsg->wParam);

    DWORD dwSaveSel = pEdit->GetSel();

    pEdit->GetWindowText(sSaveText);

        // Transmit this char to the CEdit to process it
    pEdit->SendMessage(WM_CHAR, pMsg->wParam, pMsg->lParam);

    pEdit->GetWindowText(sNewText);

        // Check if new text is ok
    if (!WildMatch(m_sWildCard, sNewText, sLimitChar) || 
          sNewText.GetLength()>iNbMaxChar)
    {
                // if not, rollback
        pEdit->SetWindowText(sSaveText);
        pEdit->SetSel(dwSaveSel);
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
I'm a French Industrial Developer,

I like codeproject! It help me to solve my problems many times...

I'm interresting in electronic an embedded module like snap (www.imsys.se), but I don't have any time to go hard in this way Wink | ;)

Comments and Discussions

 
Generalsome combinations dont match. Pin
Nic Wilson2-Feb-09 10:11
Nic Wilson2-Feb-09 10:11 
GeneralRe: some combinations dont match. Pin
Joey Rogers12-Oct-10 14:47
Joey Rogers12-Oct-10 14:47 
Generaltypo mistake in // Enf of the string and wildcard end Pin
Dmitry Efimenko11-Jan-09 20:56
Dmitry Efimenko11-Jan-09 20:56 
GeneralThere is an easy way... Pin
Yulianto.3-Feb-05 14:17
Yulianto.3-Feb-05 14:17 
GeneralRe: There is an easy way... Pin
DarkYoda M3-Feb-05 21:11
DarkYoda M3-Feb-05 21:11 
GeneralRe: There is an easy way... Pin
Yulianto.4-Feb-05 15:01
Yulianto.4-Feb-05 15:01 
GeneralRe: There is an easy way... Pin
DarkYoda M4-Feb-05 21:22
DarkYoda M4-Feb-05 21:22 
GeneralThere is an other way, Pin
Yulianto.3-Feb-05 14:17
Yulianto.3-Feb-05 14:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.