Grails: Custom validator based on a previous value of the field

前端 未结 2 379
名媛妹妹
名媛妹妹 2021-01-20 02:38

I am trying to create a custom validator for variable \'amount\' in my domain class, such that the new value should be greater than previous by 0.50.

For example, l

相关标签:
2条回答
  • 2021-01-20 02:54

    Thx Victor Sergienko, but I do a little modification on your code

    class Bid { 
      Double amount 
      ...
      static constraints = { amount(validator: { double a, Bid b -> 
        Bid tempBid = Bid.get(b.id)
        def oldValue = tempBid.getPersistentValue('amount')
        a > oldValue + 0.5 ? true : "Amount $a should be at least ${oldValue  + 0.5}" }) 
      }
    }
    

    The difference is at this line :

    Bid tempBid = Bid.get(b.id)
    def oldValue = tempBid.getPersistentValue('amount')
    

    I don't why b.getPersistentValue('amount') is always return null value, my grails version is 2.4.3

    0 讨论(0)
  • 2021-01-20 03:00

    You can try reading domainEntity.getPersistentValue('amount').

    EDIT: ... in custom validator, like:

    class Bid { 
      Double amount 
      ...
      static constraints = { amount(validator: { double a, Bid b -> 
        def oldValue = b.getPersistentValue('amount')
        a > oldValue + 0.5 ? true : "Amount $a should be at least ${oldValue  + 0.5}" }) 
      }
    }
    
    0 讨论(0)
提交回复
热议问题