Delphi Programming: Restricting User's Input Characters

Friday, May 30, 2008

For Client-Server Application or Application that Access sensitive Data it is commonly use an Authentication through a login form. you can enhance the security by restricting user to input certain characters in the login form. for example you can restrict user to input only Alphanumeric characters (A-Z,a-z,0-9) for both Username and Password Text. The advantage of this method is to minimize security hole that your application has or minimize the risk of SQL Injection. But the consequences of this method is all registered User must have their Username and Password in Alphanumeric value.

In this Tutorial i will share Delphi Script to restrict certain input characters in a Edit textbox. you must add this code on OnKeyPress Event of an Edit Component. for this tutorial you can add a TEdit(Edit1) and a label (label1).

Code for Restricting character other than Alphanumeric (A-Z,a-z,0-9) :

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);


  SelSt: Integer;

  TmpStr: string;


if not (key in ['a'..'z','A'..'Z','0'..'9',Chr(vk_Back)]) then

  with (Sender as TEdit) do


    SelSt := SelStart;

    if (Key = Chr(vk_Back)) and (SelLength <> 0) then


      TmpStr := Copy(Text,1,SelStart)+Copy(Text,SelLength+SelStart+1,255);

      label1.Caption := 'You try to Input : '+tmpstr;


    else if Key = Chr(vk_Back) then


      TmpStr := Copy(Text,1,SelStart-1)+Copy(Text,SelStart+1,255);

      label1.Caption := 'You try to Input : '+tmpstr;




      TmpStr := Copy(Text,1,SelStart)+Key+Copy(Text,SelLength+SelStart+1,255);

      label1.Caption := 'You try to Input : '+tmpstr;


    if TmpStr = '' then Exit;

    if (Key = Chr(vk_Back)) and (SelSt > 0) then Dec(SelSt)

    else if Key <> Chr(vk_Back) then Inc(SelSt);

    Key := #0;

    if SelSt = 0 then


      Text:= '';








Kofi said...


I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Delphi development

Recent Comments

Tags Cloud

Blogumulus by Roy Tanck and Amanda Fazani