Jimbob101
Jimbob101

Reputation: 21

Validation in Delphi

I'm a student and stuck on Delphi Validation. Here is my code:

begin
valid := true;
for I:=1 to Length(edtvalue.Text) do
if not (edtvalue.Text[I] in ['0'..'9','.'] )then
valid:= false;
if not valid then
begin
  showmessage ('This item is not within the range');
  DataItem1 := 0;
end
else
dataitem1 := strtofloat(edtvalue.Text);

This code reads in a value that the user inputs and checks whether it actually is an integer and detects when a user inputs letters.

However when the user inputs something else (e.g. + or @) the code doesn't work and breaks the system. Is there a way I can fix this please?

Thanks in advance

Upvotes: 0

Views: 3354

Answers (3)

Dreamer64
Dreamer64

Reputation: 1189

in 2024 in case someone need, u could make use of something simple like this:

function isValid(str: string): boolean;
var
  FRegEx : TRegEx;

begin
  result := FRegEx.IsMatch(str, '^[0-9_.]*$');
end;

Upvotes: 0

Ilyes
Ilyes

Reputation: 14928

Use TryStrToFloat :

var
  F: Double;
begin
     if not TryStrToFloat(edtvalue.Text, F) then
         showmessage ('This item is not within the range');
     else
         dataitem1 := F; 
end;

Or if you want to set DataItem1 to 0 when error :

var
  F: Double;
begin
     if not TryStrToFloat(edtvalue.Text, F) then
       begin
         showmessage ('This item is not within the range');
         DataItem1 := 0;
       end
     else
         dataitem1 := F; 
end;

Also you can create a Function to do that , like :

function IsFloat(Str: string): Boolean;
var
  I: Double;
  C: Integer;
begin
  Val(Str, I, C);
  Result := C = 0;
end;

Upvotes: 2

Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10695

I changed to use TryStrToFloat as recommended by David in the comments, you just need to declare that val variable:

var
  val: Extended;
begin
    val := 0;
    if not TryStrToFloat(edtvalue.Text, val) then
        showmessage ('This item is not within the range');
    dataitem1 := val; 
end;

Upvotes: 1

Related Questions