Recent

Author Topic: Checking the syntax of input in Edit  (Read 836 times)

dupiquvo

  • Guest
Checking the syntax of input in Edit
« on: August 03, 2020, 09:17:57 am »
I have this code to check what is entered in Edit, but there is one problem: it is not possible to erase a character if I change my mind to enter it, in an attempt to erase it, msg crashes as if the character is not correct. How can you eliminate this and make it possible to erase characters?

Code: Pascal  [Select][+][-]
  1. procedure TForm5.Edit1OnKeyPress(Sender: TObject; var Key: char);
  2. begin
  3. if (Key in ['A'..'Z','a'..'z','0'..'9','.','-']) = False then
  4.     begin
  5.      ShowMessage('The identifier cannot contain the given character');
  6.      Key:=Chr(0);
  7.     end;
  8. end;    
« Last Edit: September 16, 2020, 04:04:42 pm by marcov »

PascalDragon

  • Hero Member
  • *****
  • Posts: 5446
  • Compiler Developer
Re: Checking the syntax of input in Edit
« Reply #1 on: August 03, 2020, 09:30:36 am »
First it's clearer to use not instead of = False:

Code: Pascal  [Select][+][-]
  1. if not (Key in ['A'..'Z','a'..'z','0'..'9','.','-']) then

Second you might want to take a look at the TMaskEdit which allows you to declare a mask that the data needs to satisfy and that will automatically handle discarding invalid characters.

Leledumbo

  • Hero Member
  • *****
  • Posts: 8746
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: Checking the syntax of input in Edit
« Reply #2 on: August 04, 2020, 09:18:22 pm »
I have this code to check what is entered in Edit, but there is one problem: it is not possible to erase a character if I change my mind to enter it, in an attempt to erase it, msg crashes as if the character is not correct. How can you eliminate this and make it possible to erase characters?
Backspace is #8, Delete is #127. Yes, they both are actually characters.

lucamar

  • Hero Member
  • *****
  • Posts: 4219
Re: Checking the syntax of input in Edit
« Reply #3 on: August 04, 2020, 09:31:50 pm »
A little clearer, I think: the OnKeyUp and OnKeyDown events are fired for any key, so when you press the backspace, or delete, or home, or end, or whatever key your code goes on to test whether it's in that set and, since they are not, it launchs the ShowMessage().

One way to solve it is to make a set of permitted "edit" keys and test that the key is neither in that set nor in the "allowed" ones (A..Z, etc.); something like:

Code: Pascal  [Select][+][-]
  1. if not ((Key in EditKeys) or (Key in ['A'..'Z','a'..'z','0'..'9','.','-'])) then ...
Turbo Pascal 3 CP/M - Amstrad PCW 8256 (512 KB !!!) :P
Lazarus/FPC 2.0.8/3.0.4 & 2.0.12/3.2.0 - 32/64 bits on:
(K|L|X)Ubuntu 12..18, Windows XP, 7, 10 and various DOSes.

 

TinyPortal © 2005-2018