Link to home
Start Free TrialLog in
Avatar of PeterDelphin
PeterDelphin

asked on

Validate TEdit to allow only valid file name characters?

Hi! In a Delphi XE7 VCL application, at runtime I need to validate the text input inside a TEdit to allow only valid file name characters. In Delphi XE7 there is the System.IOUtils.TPath.HasValidFileNameChars function. How can this be applied in real-time in a TEdit component?

Unfortunately, the TEdit component has no OnValidating event. I don't want to use the OnChange event, because it looks ugly when the character appears for a short time. The validation must occur BEFORE the character appears.
Avatar of jimyX
jimyX

You can make use of one of the KeyDown/KeyUp/KeyPress events which enables you to check the pressed key before it is printed to the component.

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key in ['a'..'z', 'A'..'Z','\', ..etc]  // List all the allowed Char ranges
  if not TPath.HasValidFileNameChars(Edit1.Text+Key, ...) // Or check the key if is not valid just reset the key
    Key:= #0;
end;
Avatar of PeterDelphin

ASKER

This is not reliable, as one can paste still PASTE chars which are not allowed as filename.
ASKER CERTIFIED SOLUTION
Avatar of jimyX
jimyX

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial