Search code examples
regexgrailsgroovy

Matching last character of string fails


I cannot understand why this very simple regex is failling:

"3243" ==~ /^\d+$/ 

I want val to only be a string of numbers. The following return true:

"213213" ==~ /^\d+/ 
"213213dsadasd" ==~ /^\d+/ 

These are part of a field validation in a domain object. This is the complete code:

    static constraints = {
       intValue validator: {val,obj ->

        if(val){
            "${val}" ==~ /^[0-9]*$/ 
        }     
       }
    }

The above example will accept "321a31" or "321aa"... Not sure if the regex is wrong or something else is off...

intValue is an Integer, although the default validation would accept strings like '32112dsa'(and only store the numeric part) thats why I am trying to create a custom validator.


Solution

  • The reason the regex was not making any difference is that the values reaching the domain object field were already parsed automatically. A workaround for this can be found on this answer: Grails GORM integer validation