| msoe.edu > Dr. Durant > Courses > Examples > Custom MFC Validators |
This is a supplement to C++ Build Procedures: MFC, which is often used in CS-182 to introduce GUI programming with MFC.
The MFC ClassWizard allows you to specify simple validation rules for many data types (such as specifying that an int must be between 1 and 12). When the user enters an out-of-range value, an error message is displayed and the user is given the chance to fix the input before continuing. (Specifically, the validation occurs in response to certain events, such as when clicking the Calculate button in the MFC tutorial program.)
Sometimes you want more sophisticated validation than range checking. In general, validation rules can depend upon other data (for example, in a shipping program, a postal code would be validated differently depending upon whether the country was Canada or USA). This example shows how to implement a basic validation rule, but the concept extends to more sophisticated rules as well.
The following example walks through the steps for implementing and using a custom validation rule. It is assumed that you wish to validate a member variable named input and that your application dialog class is called CTestingDlg. The validation rule is:
"The input must be a prime number less than 10."
In order for the program to start correctly, the initial value must pass the validation test. Our first task is to ensure this.
Now we will declare the function that will perform the validation.
Now it is time to implement the validator function, which will notify the user and the GUI framework if the input is invalid.
void CTestingDlg::DDV_CustomValidate(CDataExchange *pDX, int userInput)
{
if (userInput != 2 && userInput != 3 && userInput != 5 && userInput != 7)
{
::MessageBox(NULL, "You must enter a small prime (less than 10)",
"Invalid Input", MB_OK|MB_ICONERROR);
pDX->Fail(); // notify the MFC data exchanger that validation failed
}
}
Finally, the validator function must be connected to the input to be validated.
DDV_CustomValidate(pDX, input);
This page was last updated on Friday, 28-Feb-2003 15:20:26 CST.