Search code examples
grailsgrails-orm

Grails password constraint function


I want to require users to enter a 'passphrase' since they are more secure than typical passwords people come up with.

I'm using

int numberOfWords = password.collect { 
    it.charAt(0).digit || it.charAt(0).letter ? it : ' ' 
}.join('').tokenize(' ').size()
numberOfWords >= 3

To make sure that the user creates as password containing at least 3 words to ensure security. How would I include this logic in my constraints? I tried making this into a method then just calling the method inside of constraints, but it's not working.


Solution

  • Assuming your logic/code is correct, you could include the constraint like so.

      static constraints = {
        ...
        password blank: false, validator: { value, obj ->
          int numberOfWords = value.collect {....//your logic/code
    
          if(numberOfWords < 3) {
            //returns custom error msg with this key in message.properties
            return 'className.propertyName.passphrase.validation.msg'
          }
        }
      }
    

    Here's a link to validator info