Grails custom NIP validation

In my last project I worked on application where client was identified by NIP number. Validation of such number is depend on client country, so in my domain object representing client I used custom validator.

First step was to create util objects that will calculate NIP control sum to check if number is correct. I created interface:

  1.  
  2. interface CustomValidator{
  3. Boolean validate(value);
  4. }
  5.  

Next created validator for Polish Nip number:

  1.  
  2. class NipValidatorPolish implements CustomValidator {
  3.  
  4. def static final CHECK_SUM_DIVISION = 11
  5.  
  6. def static final NIP_CORRECT_LENGTH = 10
  7.  
  8. def weights = [6, 5, 7, 2, 3, 4, 5, 6, 7]
  9.  
  10. Boolean validate(rawNip){
  11. if (!canBySumed(rawNip)){
  12. }
  13.  
  14. def checkSum = 0
  15. weights.eachWithIndex(){value, index -> checkSum += value * rawNip.getAt(index).toInteger()}
  16. return checkSum % CHECK_SUM_DIVISION == rawNip.toList().last().toInteger()
  17. }
  18.  
  19. private Boolean canBySumed(String rawNip){
  20. clearNip.size() == NIP_CORRECT_LENGTH && rawNip.isNumber()
  21. }
  22. }
  23.  

and default NIP validator for all countries where we don't want to validate controll sum:

  1.  
  2. class DefaultNipValidator implements CustomValidator {
  3. Boolean validate(rawNip){
  4. }
  5. }
  6.  

Next, I created factory that produce specified validator depends on country code:

  1.  
  2. class NipValidatorFactory {
  3. static CustomValidator produce(String countryCode){
  4. if (countryCode == CountriesCodes.Poland){
  5. return new NipValidatorPolish()
  6. }
  7. return new DefaultNipValidator()
  8. }
  9. }
  10.  

where CountriesCodes is container with countries iso codes. Finally we could use this in ours domain object :

  1.  
  2. class Country {
  3. String name
  4. String countryCode
  5. }
  6.  
  7. ...
  8.  
  9. class Client {
  10. ....
  11. Country country
  12. String nip
  13. ...
  14. static constraints = {
  15. nip (nullable: true,
  16. validator: {value, object ->
  17. return value ? NipValidatorFactory.produce(object.properties['country']?.countryCode).validate(value) : true
  18. }
  19. )
  20. }
  21. }
  22.  

No Comments yet

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.