Anonymous Human
Anonymous Human

Reputation: 1948

grails: how to check field value's validity specifically

getFieldError("user_name").rejectedValue

If I have a field as above where I've set constraints as follows:

user_name(blank: false, unique: true, email: true)

how can I check for violations specifically in each case so as to customize the error message in each case? Currently I have the following but that only works in the first case if I try to submit the form with an empty field:

def errorVal = createdUser.errors.getFieldError("user_name").rejectedValue

        if (errorVal == null)
            render(contentType: 'text/json') {["message": 'Username cannot be blank!']}
        else if (errorVal == invalid)
            render(contentType: 'text/json') {["message": 'Username must be an e-mail address!']}
        else if (errorVal == unique)
            render(contentType: 'text/json') {["message": 'Username already exists for picked institution!']}

If I try to test the second case by putting something in the field which is a non-email address, I get this error in the console:

No such property: invalid for class: com.twc.fatcaone.AdminController

Upvotes: 1

Views: 225

Answers (1)

user3578266
user3578266

Reputation:

Like the great answers others have posted, I would recommend following built in framework guidelines, however, if you want you can use the EmailValidator class to check for valid e-mail addresses. Uniqueness is already check for you but if you have additional custom criteria then you can search the database using AND on your different criteria and if the result is positive you know its not unique. Again, this may not always be the best solution.

Upvotes: 1

Related Questions