如何从OnValidate事件处理程序中检查字段的先前值?

时间:2019-01-16 19:16:14

标签: validation delphi dataset delphi-2007 tfield

我需要根据字段本身的previos值来验证TField的新值。

例如:该字段的值只能更改为更大的值

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;

我尝试检查OldValueNewValueAsVariantValue属性,但是我总是得到新值:

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;

希望有人能启发我

1 个答案:

答案 0 :(得分:0)

使用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;

但是正确的地方是OnChange事件

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;
相关问题