Fred B.
Fred B.

Reputation: 85

grails: custom validation of just one field/property

I have a "Thing" domain class, where each Thing has an record number (which is not the automatically generated id), that the user will use to access a Thing:

class Thing {
  ...
  String recordNumber
  ...
}

There is a form to look for a Thing, knowing its recordNumber:

<g:form action="search">
    <input name="recordNumber">
    <g:submitButton name="btn" value="go to this Thing"/>
</g:form>

I would like to use a validation process in this form: if the recordNumber is not found (Thing.findByRecordNumber(recordNumber) == null), then the input field must turn in red, and a tooltip must show the error message "record number not found".

As far as I know/read (I'm a grails rookie), this has to be written as a constraint in the Thing class:

static constraints = {
    recordNumber validator: { n -> Thing.findByRecordNumber(recordNumber) }
}

The problem is: I do not have in this form all the "Thing" properties to populate, just the recordNumber one, so I just can't call

new Thing(params).validate()

How to call validation on just one field, not on the whole object ?

Upvotes: 0

Views: 1613

Answers (2)

James Kleeh
James Kleeh

Reputation: 12228

If this is your main question, although I see others there:

"How to call validation on just one field, not on the whole object ?"

You can pass a list of values to validate and it will only validate those properties

new Thing(params).validate(["recordNumber"])

http://grails.org/doc/latest/ref/Domain%20Classes/validate.html

Upvotes: 3

Mr. Cat
Mr. Cat

Reputation: 3552

Validation is for constraints for domain class properties. You need an action in your controller:

def search = {
    if(params.recordNumber && Thing.findByRecordNumber(params.recordNumber)){
       redirect(action: "show", params:[id:Thing.findByRecordNumber(params.recordNumber).id])
    }else{
       flush.message = "No record found"
       render(view:'VIEW_WITH_SEARCH_FORM')
    }
}

If you want to validate without refreshing page, write a javascript code.

Upvotes: 0

Related Questions