【问题标题】:Groovy String that is constrained to uppercase限制为大写的 Groovy 字符串
【发布时间】:2014-09-24 08:16:06
【问题描述】:

我正在创建一个存储国家 ISO 代码和国家名称的域类。

class Country {
   String countryISO
   String countryName
   static constraints = {
      countryISO size:2, unique
   }
}

但我想根据 ISO 3166-1 alpha-2 标准将 countryISO 限制为仅包含大写字母。如何实现?

Tim Yates 确实指出了关于如何将其更改为大写的类似问题。问题是我真的不想改变它,我想限制它。即任何输入非大写代码的人都应该得到一个错误。

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    就这么简单

    class Country {
       String countryISO
       static constraints = {
          countryISO size:2, unique:true, validator:{ it.toUpperCase() == it }
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用matches constraint 根据正则表达式检查值:

      static constraints = {
        countryISO size:2, unique:true, matches:'[A-Z]{2}'
      }
      

      【讨论】:

      • @JeffScottBrown 它在验证方面是多余的,但它会影响 DB 模式生成,允许列是 varchar(2) 而不是 varchar(255)
      猜你喜欢
      • 2017-12-30
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多