8.3.10 Applying Constraints

URL Mappings also support Grails' unified validation constraints mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:

  1. static mappings = {
  2. "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")
  3. }

This allows URLs such as:

  1. /graemerocher/2007/01/10/my_funky_blog_entry

However, it would also allow:

  1. /graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry

This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:

  1. "/$blog/$year?/$month?/$day?/$id?" {
  2. controller = "blog"
  3. action = "show"
  4. constraints {
  5. year(matches:/\\\d{4}/)
  6. month(matches:/\\\d{2}/)
  7. day(matches:/\\\d{2}/)
  8. }
  9. }

In this case the constraints ensure that the year, month and day parameters match a particular valid pattern thus relieving you of that burden later on.