我有一个带有几个标记的编辑和单选按钮(分组在单选组中)的表单,供用户输入信息,还有一个保存按钮来保存条目。保存按钮也会关闭表单。如果有无效条目(例如,字母字符而不是数字)或某些条目留空,我想提醒用户更正错误,并且在没有空白编辑框或未选中的单选之前不要关闭表单团体。我通过引发 messageDlg 提醒用户注意错误,分别对每个编辑框和单选组进行错误检查。但是,如果用户没有更正错误并尝试保存表单,我想保持表单打开(无法关闭它)并提醒用户注意错误。只有在所有条目都有效并且没有未经检查的无线电组之后,他才能关闭表单。
根据对我之前消息的一些回复,我编写了以下代码。第一个是一个编辑框的数据输入验证示例(有几个这样的),第二个是我的保存按钮的 OnClick 事件的代码。
procedure TfrmAnalysisOptions.lbleConstraintsMaxChange(Sender: TObject);
var
I: integer;
Val, ValidEntry: string;
Chr: char;
RangeMin, RangeMax: Double;
const Allowed = ['0'..'9', '.'];
begin
Val := lbleConstraintsMax.Text;
//initialize values
ValidEntry := '';
ConstraintsMaxChange := '';
//value can contain only numerals, and "."
for I := 1 to Length(Val) do
begin
Chr := Val[I];
if not (Chr in Allowed) then
begin
MessageDlgPos('The value entered for the max value of the ' +
'constraint must contain only a numeral, a decimal ' +
'point or a negative sign.',
mtError, [mbOK], 0, 300, 300);
Exit;
end
else ValidEntry := 'OK'; //validity check for this part
end;
//max value cannot be zero or less than the min value
if not TryStrToFloat(Val, RangeMax) then Exit
else if RangeMax = 0 then
begin
MessageDlg('Max value cannot be zero.', mtError, [mbOK], 0);
Exit;
end
else if not TryStrToFloat(lbleConstraintsMin.Text, RangeMin) then Exit
else if RangeMax < RangeMin then
begin
MessageDlgPos('Max value cannot be less than Min value.',
mtError, [mbOK], 0, 300, 300);
Exit;
end
else if (RangeMax < 0) then
begin
MessageDlgPos('A constraint cannot be negative.',
mtError, [mbOK], 0, 300, 300);
Exit;
end
//final validity check
else if ValidEntry = 'OK' then ConstraintsMaxChange := 'OK'
else MessageDlgPos('There was an unexpected problem with the ' +
'value entered in the max constraints box.',
mtError, [mbOK], 0, 300, 300);
end;
这是保存按钮的 OnClick 事件的代码。如您所见,我正在检查多个条目的有效性 - 并且只有当所有条目都有效(即具有“OK”作为相应变量的值)时,我才允许关闭表单。当有无效条目时,它会正确提升 messageDlg。但是,即使在更正错误并按下“保存”按钮后,它仍会继续引发 messageDlg。
procedure TfrmAnalysisOptions.btnSaveOptionsClick(Sender: TObject);
//save input and output options
begin
//check if all the option questions have been answered
if not ((ConstraintsMinChange = 'OK') and //validation of correct entry as it is being entered
(ConstraintsMinExit = 'OK') and //validation of entry as user is moving to another entry after an incorrect entry
//several other such 'OK's
then
begin
MessageDlgPos('There is an invalid entry on the form. Please ' +
'correct it.', mtError, [mbOK], 0, 300, 300);
Exit;
end
else if //more messageDlgs if some other conditions are not met
else
begin
//save input and output options
end;
//finally if all the conditions are met, close the form
Close;
end;