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);

var

  SelSt: Integer;

  TmpStr: string;



begin

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

  with (Sender as TEdit) do

  begin

    SelSt := SelStart;

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

    begin

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

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

      end

    else if Key = Chr(vk_Back) then

    begin

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

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

    end

    else

    begin

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

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

    end;



    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

    begin

      Text:= '';

      Exit;

    end;

  end;

end;



Designtime




Runtime


0 comments:

Recent Comments

Tags Cloud

Blogumulus by Roy Tanck and Amanda Fazani