2

I have a domain constraint which I am validating like

userName(blank:false, nullable:false, Size: 5..50,matches:'^[A-Za-z\\d]*$',validator:{chkUser,user->if(user.loginService.getUser(user.organizationId,user.userName)!=null){
                                                                                                                    return[propertyName="userName"]}
                                                                                              })

So what I am trying to do is call login service and see if username exists. IF the username exists I have to return message USerName already exists. I have modified my message.properties as:

BuildUserNameCommand.userName.matches= Username Should have alphanumeric characters only
BuildUserNameCommand.userName.invalid.userName=Username already exists
BuildUserNameCommand.userName.validator.error= Username already exists

buildusernamecommand is my class name. I have also tried return['invalid.userName'] in the constraint. But still its not displaying the custom message.

Help me out please....

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
Suryateja Kosaraju
  • 493
  • 1
  • 7
  • 14

2 Answers2

3

Are you seeing any of the other custom messages for the command object like the matches one ? Are usernames uniquely global or just unique within the scope of the organisation. If globally unique validation is easy with unique:true

If just unique within scope of the organisation you could try return the string "alreadyExists" from your validator, then define the message in the form:

buildUserNameCommand.userName.alreadyExists = 'Username already exists'

If that is not working, another option would be to return false from the validator. That might then pull in the message

buildUserNameCommand.userName.validator.error= Username already exists

Note the lowercase b on the class name. Not sure if the class needs to start with a lowercase letter but in my code they do, and it would seem to be more in keeping with Grails patterns.

34m0
  • 5,755
  • 1
  • 30
  • 22
3

If you only have Users as a domain objects, it's easier to use unique constraint:

username unique: true

Then, in your case, the message code to define would be buildUserNameCommand.userName.unique - and the constraint does it all for you. It will also generate DB schema uniqueness constraint.

Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91