lsborg
lsborg

Reputation: 1201

Create custom Validator

How should I create and configure a validator class to use it as a domain class constraint? For example:

class Link {
    String url
    static constraints = { url url:true }
}

Motivation: Grails UrlValidator does not allow underline character despite it being valid, see rfc2396, section 2.3. Unreserved Characters.

Upvotes: 0

Views: 220

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

You can have a utility class in src/groovy with required validators (as static properties) and refer them in the concerned domain class.

//src/groovy
class MyValidators{
    static urlCheck = {url, obj ->
        //custom validation for url goes here.
    }
}

class Link {
    String url
    static constraints = { 
        url validator: MyValidators.urlCheck 
    }
}

If there is no need to externalize the validator to a separate utility class then you can directly use the validator in domain class as:

static constraints = {
    url validator: {value, obj -> ...} 
}

Upvotes: 5

Related Questions