Validation rules lookup mysteriously returns the record just being created

When using AS:Lookup in validation rules weird behavior has occured - lookup return newly changed value in forms not the value from database. Value (CustomerReferenceCode in product table) was not stored in database yet. This behavior only occure while moving backward in grid. When moving forward, select from database work correctly.
Validation rule is used for checking duplicity of CustomerReferenceCode. In first case get back itself in “forward” case get back value from database.
Is this feature or bug ?
(tested in both clients - web and .net - the same behavior)

Yes, after advice from Tomas, is all clear - data is saved under transaction and when validation rule parsing and lookup running all is already stored in database. Is needed exclude currently stored data by GetNotId filter. After validation, transaction will end or is bring back and validation exception is thrown.

When saving records and validating data using e.g. state events what happens is:

  1. The data get saved to the database under a transaction
  2. The event is called, loads the data from the database (they were saved before) and executes validation rules
  3. When the rule results in some exceptions, the transaction is rolled back and data are not saved.
  4. When the rule does not results in any exceptions the event workflow finishes and the transaction is committed.
  5. This could happen recursively if the event results in storing some more data.

As you see it is quite expectable then that your lookup “sees” your newly created record because it has been saved already (though under a transaction not yet committed).

Solution

So the solution to your problem (lookup for a duplicate records when saving data) is to include an additional filter in your lookup: GetNotId (it is available in IAsapEntity2).

So you will then call this:

AS:LookupValue('lookupId', 'Entity_parDuplicityCode', $myCodeForDuplicityCheck, 'Entity_parId', @MyRecordId)