2
votes

I have a form in Delphi including several TEdit boxes. I would like a way to check the validation all of the boxes kind of, currently I would have to have a boolean variable assigned to each TEdit. e.g.

Var
TEdit1Valid:boolean;
TEdit2Valid:boolean;

etc, etc for every TEdit on the form.

For the first method it would have to look something like this:

If TEdit1Valid then
    ShowMessage('Your', Edit1.Name, 'is invalid');

etc, etc for each TEdit box.

This creates many variables and I was just wondering if there is a better way to do it. One idea I had is to assign a property called Valid to a TEdit, but I don't know how to do this. With this method I could then write an array of TEdits for each TEdit and execute the following

for I := 1 to High(EditList) do
begin
if EditList[I].Valid = false then
    ShowMessage('Your ', EditList[I].Name, 'is invalid');
end

This is just an example bit of rough code that I just wrote and could use along with other things I could do iteratively like this. So could someone either suggest a good method of doing this or show me how to do the afore mentioned method.

3
Read up about arrays. Remember that the convention is to use 0 based array indices.David Heffernan
Another comment. Use the T prefix for types. Don't use it on variables.David Heffernan

3 Answers

4
votes

How about using the OnExit event handler on the TEdit controls? For example:

procedure TForm1.Edit1Exit(Sender: TObject);
begin
  with Sender as TEdit do
  begin
    if not IsValidEdit(Text) then
      ShowMessage('Your ' + Name + ' is invalid');
  end;
end;

Then apply that same OnExit event to all your TEdit controls. This example "IsValidEdit" function that I used above can validate the Text values of your TEdit, or you could just put your validation code within the OnExit event (but it would be "cleaner", in my opinion, to use a specific function to validate).

function IsValidEdit(const AValue: string): boolean;
begin
  if Length(AValue) < 5 then // not valid if length less than 5
    Result := False
  else
    Result := True;
end;
2
votes

You can use the Tag property. It an integer rather than a boolean. According to the Embarcadero help -

Tag has no predefined meaning. The Tag property is provided for the convenience of developers. It can be used for storing an additional integer value or it can be typecast to any 32-bit value such as a component reference or a pointer.

1
votes

OnExit is good for individual field validations, and is useful when you don't want the user to leave the field empty or with an improper value. It's not advisable for overall form validation, although it works.

For form validation, you're better off creating a method (eg., Validate) that's called in the OnClose handler, and if it fails, show a message, position the cursor on the field in question, then set Action := caNone, which will prevent the form from closing.