Reputation: 8043
I need to validate the new value of a TField
based on the previos value of the field itself.
e.g: the field's value can only be changed to bigger values
procedure TForm1.FldOnValidate(AField : TField);
begin
if(???) then
raise Exception.Create('The new value is not bigger than the previous one');
end;
procedure TForm1.FormCreate(Sender: TObject);
var
Dst : TClientDataSet;
Fld : TIntegerField;
begin
//dataset
Dst := TClientDataSet.Create(Self);
Dst.FieldDefs.Add('TEST', ftInteger, 0);
Dst.CreateDataSet();
Dst.Active := True;
Fld := Dst.Fields[0] as TIntegerField;
Dst.Append();
Fld.AsInteger := 5;
Dst.Post();
Fld.OnValidate := FldOnValidate;
//this should be ok (from 5 to 6)
Dst.Edit;
Fld.AsInteger := 6;
Dst.Post;
//this should not pass the validation (from 6 to 5)
Dst.Edit;
Fld.AsInteger := 5;
end;
I've tried to check the OldValue
, NewValue
, AsVariant
and Value
properties but I always get the new value:
procedure TForm1.FldOnValidate(AField : TField);
begin
ShowMessage(
'OldValue = ' + VarToStr(AField.OldValue) + sLineBreak +
'NewValue = ' + VarToStr(AField.NewValue) + sLineBreak +
'AsVariant = ' + VarToStr(AField.AsVariant) + sLineBreak +
'Value = ' + VarToStr(AField.Value)
);
end;
Hope someone could enlighten me about that
Upvotes: 0
Views: 1899
Reputation: 14928
Use Unassigned
procedure TForm1.FldOnValidate(AField : TField);
begin
if Sender.OldValue <> Unassigned then
if Sender.NewValue <= Sender.OldValue then
raise Exception.Create('The new value is not bigger than the previous one');
end;
But the right place is OnChange
event
procedure TForm1.ClientDataSet1ValChange(Sender: TField);
begin
if Sender.OldValue <> Unassigned then
if Sender.NewValue <= Sender.OldValue then
raise Exception.Create('The new value is not bigger than the previous one');
end;
Upvotes: 0