C++Builder - ClientDataSet, part 3ValidatingValidating a database record includes two aspects:
Preparations
Validating the ID fieldWe've split our checking into two parts: firstly, we check the ID with the function ValidID(). Before posting a record, we check if the ID contains 4 characters. That's easy.
Solution: we use a second clientdataset that is a clone of cdsArt, aptly named cdsArtClone. We index the clone dataset on ID. bool TForm1::ValidID(String& Err) // Err is passed by REFERENCE
{
bool Result = true;
String ID = cdsArt->FieldByName("ID")->AsString;
int LenID;
Err = "";
LenID = ID.Length();
Result = (LenID == 4);
if (! Result)
Err = " Invalid ID: must be 4 characters ";
else {
cdsArtClone->CloneCursor(cdsArt, true, false);
cdsArtClone->IndexFieldNames = "ID";
// Note double brackets with ARRAYOFCONST
if (cdsArtClone->FindKey(ARRAYOFCONST((ID)))) {
if (cdsArt->State == dsInsert) {
Result = false;
Err = "Invalid, ID already exists";
}
else { // editing
if (cdsArt->FieldByName("ID")->AsString != OldID) {
Result = false;
Err = "Invalid, ID already exists";
}
}
}
}
return Result;
}
Note that in addition to returning a value of true / false, this function also
sets a message in parameter Err, that was passed by reference, thus modifying the original value of Err in function btnOKClick(). void __fastcall TForm1::btnOKClick(TObject *Sender) { String Err = ""; // for receiving error messages bool ValidRecord = ValidID(Err); // more statements... if (ValidRecord) { // post record, and so on... } else { // invalid ID // display error message if (cdsArt->State == dsInsert) ShowStatus("inserting", Err); else ShowStatus("editing", Err); } } Validating Name, Price and StockFunction ValidData() checks if the field Name is not empty, and if there is no negative value in Price nor in Stock: bool TForm1::ValidData(String& Err) // Err is passed by REFERENCE
{
bool Result = true;
Err = "";
Result = (Trim(cdsArt->FieldByName("Name")->AsString) != "");
if (! Result)
Err = "Invalid, NAME can not be empty";
else {
Result = ((cdsArt->FieldByName("Price")->AsFloat) >= 0);
if (! Result)
Err = "Invalid, PRICE can not be negative";
else {
Result = ((cdsArt->FieldByName("Stock")->AsInteger) >= 0);
if (! Result)
Err = "Invalid, STOCK can not be negative";
}
}
return Result;
}
|
Table of contents
1. Intro / Setup 2. Load / Save 3. Validating 4. Find / Filter 5. Report generator
|