In continuation of my earlier post on the cross-field date validation , I'm going to discuss another method using grails controller.
The following code in "save" and "update" method of the controller validates the date fileds used in the student domain object that is discussed in the previous post
def save = {
def studentInstance = new Student (params)
if (studentInstance.endDate.before(studentInstance.startDate))
{
studentInstance.errors.rejectValue('endDate', 'student.endDate.shouldbegreater')
}
...
..
}
Note that the code highlighted as bold is the addition to the boiler-plate code generated by using the grails command "grails generate-all" on the domain class "Student"
Following message is to be added to the "messages.properties" file
vendor.contractEndDate.shouldbegreater= End Date should be greater than the start date.
The method used in controllers gives more control on validation rather than the method used in the domain class.
In scenarios where we need to validate "endDate" field referring to more than one domain object, having the validation in contoller is the right place.
Eg: If we have another domain class, "Course" with fields "courseStartDate" and "courseEndDate", we can apply a validation in rule saying Student.enddate <= Course.courseEndDate.
The following code in "save" and "update" method of the controller validates the date fileds used in the student domain object that is discussed in the previous post
def save = {
def studentInstance = new Student (params)
if (studentInstance.endDate.before(studentInstance.startDate))
{
studentInstance.errors.rejectValue('endDate', 'student.endDate.shouldbegreater')
}
...
..
}
Note that the code highlighted as bold is the addition to the boiler-plate code generated by using the grails command "grails generate-all" on the domain class "Student"
Following message is to be added to the "messages.properties" file
vendor.contractEndDate.shouldbegreater= End Date should be greater than the start date.
The method used in controllers gives more control on validation rather than the method used in the domain class.
In scenarios where we need to validate "endDate" field referring to more than one domain object, having the validation in contoller is the right place.
Eg: If we have another domain class, "Course" with fields "courseStartDate" and "courseEndDate", we can apply a validation in rule saying Student.enddate <= Course.courseEndDate.
Comments
Post a Comment