2014-09-24 80 views
0

我正在创建一个存储国家ISO代码和国家/地区名称的域类。Groovy约束为大写的字符串

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

但我想限制countryISO只包含大写字母作为每ISO 3166-1的α-2标准。如何实现?

蒂姆耶茨确实指出,有关于如何将其更改为大写的类似问题。问题是我不想改变它,我想限制它。 I.e任何输入不是大写的代码的人都会遇到错误。

回答

1

那样简单

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

你可以使用一个matches constraint来对正则表达式检查该值:

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

@JeffScottBrown它是多余的验证条件,但它影响了DB模式的产生,使该列是varchar(2)而不是varchar(255) – 2014-09-24 12:14:29