The only case insensitive constraint in Grails

How can I, in principle, fulfill a unique constraint for a string data type.

class User{ String username String Email static hasMany = [roles:Roles] static constraints = { Email(email:true) username(unique:true) } } 

Is there an easy way to implement username(unique: true)

Or do you need to manually check the database using methods such as .findByNameLike ?

The username must be unique, but uniqueness must be case insensitive.

+5
source share
3 answers

So, if you want to have unique and case-insensitive user names, there are two possible approaches.

Plain:

  • Store them in upper or lower case and use a unique constraint.

or, relative to performance, more expensive:

  • Save them in a mixed case and use a custom validator that validates the database by comparing data and existing case-insensitive usernames.

Now it depends on whether you just want to give the user the ability to enter his username in case he wants (the first opportunity), or you want to save the usernames argument to display the reasons (second possibility).

Your question sounds like a second, so the custom validator will look like this:

 class User { String username String email static hasMany = [roles:Roles] static constraints = { email(email:true) username(validator: { return !User.findByUsernameILike(it) }) } } 

Hope this helps.

[change]

As Henry notes in his comment, the validator above will cause problems when users can change their username.

Quick and dirty, but I think this solves the problem:

 username(validator: { val, obj -> def similarUser = User.findByUsernameILike(val) return !similarUser || obj.id == similarUser.id }) 

Beware, it has not been tested, and I'm not sure if you can define variables in validators.

Meta: I would never let users change their username;)

+13
source

To add another solution to the @air_blob quick and dirty solution, have you tried this?

 username(validator: { val, obj -> return !User.findByUsernameIlikeAndIdNotEqual(val, obj.id) }) 
+2
source

username(unique:true) is a valid restriction.

To make the case of constraints insensitive, you need to write your own validator. See this discussion thread for more details.

+1
source

All Articles